LoginSignup
0
0

More than 3 years have passed since last update.

tkinterのEntryから取得した値をリストの末尾に追加する

Posted at

背景

クラスがよくわかっていなかったので、自らの勉強を兼ねて書いてみた。

クラスのコードを試しに書いてみる

試しに、以下のような簡単なクラスを書いてみる。

tkclass.py
class x:
    def __init__(self,x): #クラスを実行したときに必ず実行されるメソッド
        self.x = x
    def go(self):
        self.x = x #__init__で取得した変数xを引き継いでいる。
        print(x)

ここで、Xというのがクラスの名前である。
また、クラス内での関数はメソッドと呼ばれる。

ただ、ここでxの内容を入れてもこのままでは呼び出されない。
ここで、インスタンスというものを定義する

test.py
yobidashi =x(10)

このyobidashiが、インスタンス名(クラスを呼び出したいときの名前)である。
(10)は、xに入れたい引数を入れている。

test.py
yobidashi =x(10)
yobidashi.go()

実際にインスタンスを呼び出したいときは、インスタンス名.メソッド名(引数が必要な場合は引数)で呼び出すことができる。
ここでは、yobidashi.go()で、yobidashiインスタンスのうち、goメソッドだけ呼び出している

出力結果としてはこうなる。

test.py
10

Tkinterでクラスを作ってみる

内容としては、EntryBoxに入れた文字を指定されたリストの末尾に代入し、その文字をStringVar()でラベルを更新する

test.py
import tkinter as tk

#客リスト
namelist=[]
#commandにクラスのメソッドを当ててみるテスト
class disp():
    e=0
    l=0
    #土台を作成
    def tki(self):
        global e
        global l
        root = tk.Tk()
        root.geometry("640x480")
        l = tk.StringVar()
        l.set("あ")
        la = tk.Label(textvariable=l,font=("Meiryo UI",60))
        la.pack()
        e = tk.Entry(width=20)
        e.pack()
        bt = tk.Button(text="登録",width=20,height=5,command=self.nameappend)
        bt.pack()
        root.mainloop()
    #list_append
    def nameappend(self):
        global e
        global l
        global namelist
        get1 = e.get()
        namelist.append(get1)
        if str(get1) == "":
            l.set("名前を入力してください!")
        else:
            l.set(str(get1)+"さんを名前リストに追加しました")
        print(namelist)
#インスタンス作成
d = disp()
d.tki()

出来上がりイメージ
capture1.PNG

capture2.PNG

capture3.PNG

参考サイト

buttonのcommandにクラスのメソッドを割り当てる方法 https://www.shido.info/py/tkinter5.html
super()の使い方 https://teratail.com/questions/85379

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0