2016-02-15 95 views
0

我有一個Tkinter GUI我創建並希望添加線程在某個時刻,併爲GUI設置一個類。當我添加這個類時,一切都像以前那樣工作,但是我有一個關閉程序的按鈕(root.destroy())。這是一個正在發生的事情的例子。問題與Tkinter和銷燬

這是我開始用:

#!/usr/bin/python 

from Tkinter import * 
import serial 
import time 

aSND = '/dev/ttyACM0' #Sets arduino board to something easy to type 
baud = 9600 #Sets the baud rate to 9600 
ser = serial.Serial(aSND, baud) #Sets the serial connection to the Arduino board and sets the baud rate as "ser" 


def end(): 
    ser.write('d') 
    time.sleep(1.5) 
    root.destroy() 

root = Tk() 
root.geometry('800x480+1+1') 
root.title('Root') 
buttona = Button(root, text='End Program', command=end) 
buttona.place(x=300, y=75) 

root.mainloop() 

如果我改變計劃,包括類,然後我得到這個錯誤信息:

Exception in Tkinter callback 
Traceback (most recent call last): 
    File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1437, in __call__ 
    return self.func(*args) 
    File "/home/pi/projects/examplegui.py", line 32, in end 
    LCARS.destroy() 
NameError: global name 'root' is not defined 

下面是與類相同的程序補充:

#!/usr/bin/python 

from Tkinter import * 
import serial 
import time 

aSND = '/dev/ttyACM0' #Sets the arduino board to something easy to type 
baud = 9600 #Sets the baud rate to 9600 
ser = serial.Serial(aSND, baud) #Sets the serial connection to the Arduino board and sets the baud rate as "ser" 

class program1(): 

    def end(): 
     ser.write('d') 
     time.sleep(1.5) 
     root.destroy() 

    root = Tk() 
    root.geometry('800x480+1+1') 
    root.title('Root') 
    buttona = Button(root, text='End Program', command=end) 
    buttona.place(x=300, y=75) 

program1.root.mainloop() 

謝謝

羅伯特

回答

0

你的班級設計很差。

下面是一個簡化,工作溶液:

from Tkinter import * 


class Program1(object): 

    def __init__(self): 
     self.root = Tk() 
     self.root.geometry('800x480+1+1') 
     self.root.title('Root') 
     self.buttona = Button(self.root, text='End Program', command=self.end) 
     self.buttona.place(x=300, y=75) 

    def end(self): 
     self.root.destroy() 

Program1().root.mainloop()