2016-11-26 2 views
-1

이것은 첫 번째 파이썬 프로그램입니다. 내가 torricelli의 draintime 계산기를 만들려고 노력하고 있지만 '명확한 결과'버튼이 작동하지 않습니다. 계산 된 결과를 지우고 싶습니다.Python Tkinter GUI : '결과 지우기'버튼이 작동하지 않습니다.

Traceback (most recent call last): 
    File "C:\Users\David \Desktop File\GUI_DrainTime_Calculator.py", line 83, in clear 
    drain_label.destroy() 
NameError: name 'drain_label' is not defined 

이 나가서 설명하자면 NameError가 계속 왜 나를 파악 도와주세요 :

나는이 오류가 발생합니다. 이것은 범인입니다 :

drain_label = Label(
    WIN, 
    font=('Helvetica', 8, 'bold'), 
    text="The time it takes for the liquid to drain is: %.0f hour, %.0f minutes, and %.0f seconds." % (hr, Min, sec)).pack(side=BOTTOM) 

def clear(): 
    drain_label.destroy() 
    Clearbtn = Button(WIN, text="Clear Results", font('Helvetica',7,'bold'), fg='black',command=clear) 
    Clearbtn.configure(background='grey') 
    Clearbtn.pack(side=TOP,pady=5) 

감사합니다!

답변

0

drain_label 내가 최대한 글로벌 변수를 사용하지 않도록 조언을하지만, 따라서 함수, 함수의 인수로 drain_label을 통과하려고하거나 global을 어디서나 그 정의/선언을 볼 수 없습니다, global 변수 아니다 당신의.

2

라벨에 textvariable을 사용해보세요. 또한 프로그램에 클래스를 사용하는 것이 좋습니다.

import tkinter as tk 
from tkinter import ttk 

class Calculator: 
    def __init__(self, master): 

     frame = tk.Frame(master) 

     self.text_var = tk.StringVar() 
     hr, min, sec = 1, 4, 20 
     text = 'drain time = %.0f Hr, %0f Min, %.0f Sec' % (hr, min, sec) 

     drain_label = ttk.Label(frame, textvariable=self.text_var).pack() 

     clear_button = ttk.Button(frame, text='clear', command=self.destroy).pack() 

     frame.pack() 

    def destroy(self): 
     self.text_var.set('') 

root = tk.Tk() 
app = Calculator(root) 
root.mainloop() 

당신은 얻을 문자열 변수를 설정하기 위해 .get().set() 방법과 함께 tk.StringVar()를 사용할 수 있습니다. hr, min, sec에 문자열 변수를 사용하고 단추를 사용하여 문자열을 전달할 수도 있습니다.

관련 문제