我创建了一个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()
谢谢,
罗伯特
答案 0 :(得分: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()