猿问

Tkinter 甚至不能调用一个简单的“按钮”

从简单的 Tkinter 课程开始,即使简单的代码不起作用,我也陷入了困境:


import tkinter as tk

root = tk.Tk()

b = tk.Button(root, text='button'); b.pack()

...


Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

  File "/Users/../anaconda3/lib/python3.6/tkinter/__init__.py", line 2366, in __init__

    Widget.__init__(self, master, 'button', cnf, kw)

  File "/Users/../anaconda3/lib/python3.6/tkinter/__init__.py", line 2296, in __init__

    (widgetName, self._w) + extra + self._options(cnf))

_tkinter.TclError: can't invoke "button" command: application has been destroyed

并且找不到原因,考虑到此代码来自官方文档。


另一方面,另一个代码有效:


import tkinter as tk



class Application(tk.Frame):

    def __init__(self, master=None):

        super().__init__(master)

        self.master = master

        self.pack()

        self.create_widgets()


    def create_widgets(self):

        self.hi_there = tk.Button(self)

        self.hi_there["text"] = "Hello World\n(click me)"

        self.hi_there["command"] = self.say_hi

        self.hi_there.pack(side="top")


        self.quit = tk.Button(self, text="QUIT", fg="red",

                              command=self.master.destroy)

        self.quit.pack(side="bottom")


    def say_hi(self):

        print("hi there, everyone!")



root = tk.Tk()

app = Application(master=root)

app.mainloop()

我试图tk从 conda:更新conda install -c anaconda tk,但没有任何变化。想不通为什么


呼唤远方
浏览 485回答 2
2回答
随时随地看视频慕课网APP

相关分类

Python
我要回答