4

以下は私のスクリプトです。基本的に、ユーザーは入力ボックスに数字を入力するよう求められます。ユーザーが数値を入力して [OK] をクリックすると、ユーザーが [入力] ボックスに入力した数値に応じて、ラベルとボタンの組み合わせが表示されます。

from Tkinter import *

root=Tk()

sizex = 600
sizey = 400
posx  = 0
posy  = 0
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))

def myClick():
    myframe=Frame(root,width=400,height=300,bd=2,relief=GROOVE)
    myframe.place(x=10,y=10)
    x=myvalue.get()
    value=int(x)
    for i in range(value):
        Mylabel=Label(myframe,text=" mytext "+str(i)).place(x=10,y=10+(30*i))
        Button(myframe,text="Accept").place(x=70,y=10+(30*i))

mybutton=Button(root,text="OK",command=myClick)
mybutton.place(x=420,y=10)

myvalue=Entry(root)
myvalue.place(x=450,y=10)

root.mainloop()

通常、ラベルウィジェットを作成するときは、次のようにします

mylabel=Label(root,text='mylabel')
mylabel.pack()

後でラベルのテキストを変更したい場合は、これを行うだけです

mylabel.config(text='new text')

しかし今、forループを使用してすべてのラベルを一度に作成しているので、ラベルが作成された後に個々のラベルに対処する方法はありますか? たとえば、ユーザーが入力ボックスに「5」と入力すると、プログラムは 5 つのラベル + 5 つのボタンを表示します。個々のラベルのプロパティ (つまり、label.config(..)) を変更する方法はありますか?

4

1 に答える 1

3

もちろん!ラベルのリストを作成し、それぞれを呼び出すplaceだけで、後でそれらを参照して値を変更できます。そのようです:

from Tkinter import *

root=Tk()

sizex = 600
sizey = 400
posx  = 0
posy  = 0
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))

labels = []

def myClick():
    del labels[:] # remove any previous labels from if the callback was called before
    myframe=Frame(root,width=400,height=300,bd=2,relief=GROOVE)
    myframe.place(x=10,y=10)
    x=myvalue.get()
    value=int(x)
    for i in range(value):
        labels.append(Label(myframe,text=" mytext "+str(i)))
        labels[i].place(x=10,y=10+(30*i))
        Button(myframe,text="Accept").place(x=70,y=10+(30*i))

def myClick2():
    if len(labels) > 0:
        labels[0].config(text="Click2!")
    if len(labels) > 1:
        labels[1].config(text="Click2!!")

mybutton=Button(root,text="OK",command=myClick)
mybutton.place(x=420,y=10)

mybutton2=Button(root,text="Change",command=myClick2)
mybutton2.place(x=420,y=80)

myvalue=Entry(root)
myvalue.place(x=450,y=10)

root.mainloop()

また、注意してください!Mylabel=Label(myframe,text=" mytext "+str(i)).place(x=10,y=10+(30*i))元のコードの代入では、メソッドが None を返すMylabelため、その呼び出しは None に設定されます。上記のコードのように、呼び出しを独自の行にplace分けたいとします。place

于 2013-04-04T05:28:03.773 に答える