2

I looked through a tutorial on using Tkinter and saw that the following code:

>>> from Tkinter import *
>>> win=Tk()

This should produce a box with the title Tk and nothing else. However, when I try this code out no such box appears. I'm not getting any errors so I suspect it's working as intended. Is it possible that there are additional steps I have to take if I'm on a mac?

from Tkinter import *

root = Tk()

w = Label(root, text="Hello, world!")
w.pack()

root.mainloop()

This code runs automatically, however, in the guide it suggests that I use $ python hello1.py to run this code, which doesn't work. Any ideas on why this might be?

However, this larger block does not work:

from Tkinter import *

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.button = Button(
            frame, text="QUIT", fg="red", command=frame.quit
            )
        self.button.pack(side=LEFT)

        self.hi_there = Button(frame, text="Hello", command=self.say_hi)
        self.hi_there.pack(side=LEFT)

    def say_hi(self):
        print "hi there, everyone!"

root = Tk()

app = App(root)

root.mainloop()
root.destroy() # optional; see description below

The issue seems to have something to do with mainloop but I'm confused because at the same time that earlier block worked just fine with a root.mainloop() part.

4

2 回答 2

3

您是否在 IDLE 中运行此代码?

在终端(不在 IDLE 中)尝试上面的代码,然后它将按预期工作。

于 2013-07-25T16:52:11.030 回答
0

因此,如果您想尝试在终端中运行它,您应该按照以下步骤操作

注意-'我发现正在运行的程序是涉及 tkinter Gui 的终端经常会崩溃,但它可能对你有用'

1st - Open Terminal
2nd - Type 'python3.4' then press space bar once
3rd - Open a Finder window
4th - Go to where you saved your python file in the Finder window
5th - Once you have located the file in Finder, drag the file into the Terminal window
6th - Press enter, and enjoy your python program.

另一个注释 - “听起来你需要一个更好的 Python IDE,你应该试试 PyCharm,它是一个很棒的 Python IDE,你可以编写和运行包含 tkinter 东西的 Python 程序”

你可以在这里下载 PyCharm https://www.jetbrains.com/pycharm/

于 2014-11-11T07:44:52.727 回答