114
114

Reputation: 926

Creating a User Interface Using Tkinter (Python)

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.

Upvotes: 2

Views: 1267

Answers (2)

Jonty Morris
Jonty Morris

Reputation: 807

So if you want to try and run it in Terminal you should follow the steps below

note- 'I find that running programs is Terminal that involve a tkinter Gui will often crash for me, however it may work for you'

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.

another note - 'It sounds like you need a better Python IDE, you should try out PyCharm it is a great Python IDE which you can code and run python programs in including tkinter stuff'

You can download PyCharm here https://www.jetbrains.com/pycharm/

Upvotes: 0

falsetru
falsetru

Reputation: 369444

Do you run this code in IDLE?

Try above code in terminal (not in IDLE), then it will work as expected.

Upvotes: 3

Related Questions