2017-12-08 5 views
-1

확장 가능한 카운터를 만들려고합니다.루프에 정의 된 레이블의 텍스트 변경

첫 번째 창에서 원하는 카운터 수를 입력하십시오.

두 번째 창에는 레이블에 하나를 추가하는 데 사용되는 레이블과 단추가 있습니다. _ 전입니다

name 'label_' is not defined 

: 그러나 이것은 내가 오류입니다

from tkinter import * 

root = Tk() 

def newWindow(): 
    window = Toplevel() 
    for i in range(int(textbox.get())): 
     exec("global label"+ str(i)) 
     exec("label" + str(i) + " = Label(window, text = '0')") 
     exec("label" + str(i) + ".grid(row = 0, column = i)") 
     exec("global button"+ str(i)) 
     exec("button" + str(i) + " = Button(window, text = 'Add', command = lambda: setText(label" + str(i) + "))") 
     exec("button" + str(i) + ".grid(row = 1, column = i)") 

def setText(label): 
    label.config(text = str(int(label.cget("text")) + 1)) 

textbox = Entry(root) 
textbox.grid(row = 0) 
submitButton = Button(root, text = "Submit", command = newWindow) 
submitButton.grid(row = 0, column = 1) 

root.mainloop() 

:

여기 내 코드입니다.

전역으로 설정해도 문제가 해결되지 않았습니다.

도와주세요.

+0

완전한 오류 메시지가 표시됩니다. – mrCarnivore

답변

0

이런 식으로 exec을 사용하는 경우 매우 잘못된 행동을하고있는 것입니다.

간단한 해결책은 위젯을 목록이나 사전에 추가하는 것입니다. 이 특별한 경우에는 버튼 커맨드 어디서나 레이블을 참조하는 적이 없기 때문에이 경우는 필요하지 않습니다. 여기

는 작업 예제 :

def setText(i): 
    label = labels[i] 
    label.configure(...) 
... 
button = Button(..., command=lambda i=i: setText(i)) 
: 당신이, 당신이 당신의 버튼을 인덱스에 통과 할 수 labels을 사용하고 setText는 사전에서 위젯을 얻을 수 있도록하고 싶었다면

from tkinter import * 

root = Tk() 

def newWindow(): 
    global labels 
    window = Toplevel() 
    labels = {} 
    for i in range(int(textbox.get())): 
     label = Label(window, text='0') 
     button = Button(window, text='Add', command = lambda l=label: setText(l)) 

     label.grid(row=0, column=i) 
     button.grid(row=1, column=i) 

     # this allows you to access any label later with something 
     # like labels[3].configure(...) 
     labels[i] = label 

def setText(label): 
    label.config(text = str(int(label.cget("text")) + 1)) 

textbox = Entry(root) 
textbox.grid(row = 0) 
submitButton = Button(root, text = "Submit", command = newWindow) 
submitButton.grid(row = 0, column = 1) 

root.mainloop() 

관련 문제