我有一个我创建的Tkinter GUI,想在某个时候添加线程,并为GUI设置一个类。当我添加这个类时,一切都像以前一样工作,但是我有一个关闭程序的按钮(root.destroy()),这里是一个发生了什么的例子。
这就是我要开始的内容:
#!/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()谢谢,
罗伯特
发布于 2016-02-16 05:42:50
您的类的设计很差。
以下是一个简化的、有效的解决方案:
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()https://stackoverflow.com/questions/35419236
复制相似问题