首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Tkinter和destroy问题

Tkinter和destroy问题
EN

Stack Overflow用户
提问于 2016-02-16 04:42:48
回答 1查看 472关注 0票数 1

我有一个我创建的Tkinter GUI,想在某个时候添加线程,并为GUI设置一个类。当我添加这个类时,一切都像以前一样工作,但是我有一个关闭程序的按钮(root.destroy()),这里是一个发生了什么的例子。

这就是我要开始的内容:

代码语言:javascript
复制
#!/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()

如果我将程序更改为包含一个类,则会收到以下错误消息:

代码语言:javascript
复制
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

下面是添加了类的相同程序:

代码语言:javascript
复制
#!/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()

谢谢,

罗伯特

EN

回答 1

Stack Overflow用户

发布于 2016-02-16 05:42:50

您的类的设计很差。

以下是一个简化的、有效的解决方案:

代码语言:javascript
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35419236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档