Can't create Tkinter window method - python

I have the following code. This creates a dialog box just fine.
import tkinter as tk
import tkinter.ttk as ttk
class Window(ttk.Frame):
def __init__(self, master=None):
super().__init__(master, padding=2) # Creates self.master
helloLabel = ttk.Label(self, text="Hello Tkinter!")
quitButton = ttk.Button(self, text="Quit", command=self.quit)
helloLabel.pack()
quitButton.pack()
self.pack()
#self.create_widgets()
#self.create_layout()
# def create_widgets(self):
# pass
# def create_layout(self):
# pass
application = tk.Tk()
application.title("Window")
Window(application)
application.mainloop()
How come when I uncomment the following two lines in the above code the code breaks?
def create_widgets(self):
pass
I'm using python 3.4 32 bit on Windows 7 64-bit.

Related

TKinter start python button (first time using tkinter)

I have a script, and woult like to have some imputs, outputs (as in the terminal) and a start running script.
How can I do this?
this is what I have for now:
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
exitButton = Button(self, text="Run", command=self.clickExitButton)
exitButton.place(x=0, y=0)
def clickrunButton(self):
run() #this doesnt work
root = Tk()
app = Window(root)
# set window title
root.wm_title("Tkinter window")
# show window
root.mainloop()
You have to place your app in the root, for example with pack(). You also have to change the name of the function, because it doesn't match the one you give to the button command.
from tkinter import *
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.pack() # Window is packed in its master.
exitButton = Button(self, text="Run", command=self.clickrunButton)
exitButton.pack()
def clickrunButton(self):
self.run() # Now this work
def run(self):
print('Something')
root = Tk()
app = Window(root)
# set window title
root.wm_title("Tkinter window")
# show window
root.mainloop()

How to destroy a window after opening a new one?

I am working on a game called 'Flag Quiz' using tkinter. I have a script called mainmenu where I can choose between an easy mode and a hard mode. If I click on one of the buttons the recent mainmenu window disappears and a new tkinter window opens.
Here is my mainmenu script:
from tkinter import *
import tkinter as tk
from hardmode import HardApp
from easymode import EasyApp
class TitleScreen(tk.Tk):
def __init__(self):
super().__init__()
self.title('Flag Quiz')
self.geometry('600x600')
self.resizable(0,0)
self.make_widgets()
def make_widgets(self):
self.background = PhotoImage(file = './background.png')
self.label = Label(self, image=self.background)
self.label.place(x=0, y=0, relwidth=1, relheight=1)
self.easy = Button(self, text="Easy Mode", height=2, width=6, font=('default', 20), command=self.play_easy)
self.hard = Button(self, text="Hard Mode", height=2, width=6, font=('default', 20), command=self.play_hard)
self.easy.place(relx=0.5, rely=0.45, anchor=CENTER)
self.hard.place(relx=0.5, rely=0.55, anchor=CENTER)
def play_easy(self):
self.withdraw()
self.app = EasyApp()
#self.app.start()
def play_hard(self):
self.withdraw()
self.app = HardApp()
#self.app.start()
def start(self):
self.mainloop()
TitleScreen().start()
And here is my easy mode script:
import tkinter as tk
from tkinter import *
import random
import os
import json
class EasyApp(tk.Toplevel):
def __init__(self):
super().__init__()
self.title('Flag Quiz')
self.geometry('')
self.resizable(0,0)
self.score = 0
self.create_widgets()
def create_widgets(self):
# variables
self.user_guess = StringVar(self)
self.text = StringVar(self)
self.text.set(" ")
# initial image
self.scoretext = Label(self, text="Score: ").pack(side='top', fill='x')
self.scorevalue = Label(self, text=self.score).pack(side='top', fill='x')
self.file = random.choice(os.listdir('pngs'))
self.randimg = PhotoImage(file='pngs/{}'.format(self.file))
self.randimg = self.randimg.subsample(2, 2)
self.panel = Label(self, image=self.randimg)
self.panel.pack()
self.country, self.ext = self.file.split('.')
self.countries = self.load_lookup()
self.countryname = [country for country in self.countries if country['alpha2'] == self.country]
self.s = []
for i in range(0,3):
country = random.choice(self.countries)
self.s.append(country['de'])
self.s.append(self.countryname[0]['de'])
random.shuffle(self.s)
self.btndict = {}
for i in range(4):
self.btndict[self.s[i]] = Button(self, text=self.s[i], height=2, width=35, font=('default', 20), command=lambda j=self.s[i]: self.check_input(j))
self.btndict[self.s[i]].pack()
def check_input(self, d):
if d != self.countryname[0]['de']:
print("Falsch")
else:
self.score += 5
for widget in self.winfo_children():
widget.destroy()
self.create_widgets()
def load_lookup(self):
with open('lookup.json') as file:
self.obj = file.read()
self.countryobj = json.loads(self.obj)
return self.countryobj
# def start(self):
# self.mainloop()
After clicking the close button (the default button on windows/osx to close a window) the window from my easy mode app disappears but PyCharm says that my program is still running.
I made some investigations and removed the self.withdraw() function in the function play_easy(self) in my mainmenu script. So now the mainmenu is still open after I click on the easy mode button. If I'm closing both windows now, the program fully ends.
Replacing self.withdraw() with self.destroy() is not working. The main menu is closed, but a new empty window opens instead.
Any suggestions on how to handle this problem so that my program fully ends if I click the close button within the easy/hard mode window?
You have two windows - main window created with Tk and subwindow created with Toplevel. When you use close button to close main window then it should also close all subwindows but when you close subwindow then it doesn't close main window (parent window) but only own subwindows - because usually it can be useful to display again main window to select other options and open again subwindow.
One of the methods is to destroy first window and use Tk to create new window.
But in this method you can't use some button in second window to go back to first window - and sometimes it can be problem. Even if you create again first window then it will not remeber previous values (if you have some Entry or other widgets to set values)
# from tkinter import * # PEP8: `import *` is not preferred`
import tkinter as tk
class EasyApp(tk.Tk): # use `Tk` instead of `Toplevel`
def __init__(self):
super().__init__()
self.scoretext = tk.Label(self, text="EasyApp")
self.scoretext.pack()
#def start(self):
# self.mainloop()
class TitleScreen(tk.Tk):
def __init__(self):
super().__init__()
self.button = tk.Button(self, text="Easy Mode", command=self.play_easy)
self.button.pack()
def play_easy(self):
self.destroy() # destroy current window
self.app = EasyApp()
def start(self):
self.mainloop()
TitleScreen().start()
Other method is to use self.wm_protocol("WM_DELETE_WINDOW", self.on_close) to execute function on_close when you use close button and in this function destroy main window (master).
This way you can still use Button to go back to main window which will remember previous content.
# from tkinter import * # PEP8: `import *` is not preferred`
import tkinter as tk
class EasyApp(tk.Toplevel): # still use `Toplevel`
def __init__(self, master): # send main window as master/parent
super().__init__(master) # it will also set `self.master = master`
self.scoretext = tk.Label(self, text="EasyApp")
self.scoretext.pack()
self.button = tk.Button(self, text="Go Back", command=self.go_back)
self.button.pack()
# run `on_close` when used `close button`
#self.protocol("WM_DELETE_WINDOW", self.on_close)
self.wm_protocol("WM_DELETE_WINDOW", self.on_close)
def go_back(self):
self.destroy() # destroy only current window
self.master.deiconify() # show again main window
def on_close(self):
self.destroy() # destroy current window
self.master.destroy() # destroy main window
class TitleScreen(tk.Tk):
def __init__(self):
super().__init__()
self.entry = tk.Entry(self)
self.entry.pack()
self.entry.insert('end', "You can change text")
self.button = tk.Button(self, text="Easy Mode", command=self.play_easy)
self.button.pack()
def play_easy(self):
self.withdraw()
self.app = EasyApp(self) # send main window as argument
def start(self):
self.mainloop()
TitleScreen().start()
Here's a fairly simple architecture for doing what you want. An application class is derived from Tk() which hides the default "root" window it normally displays and all the windows it does display are subclasses of a custom Toplevel subclass I've named BaseWin.
This class is just a Toplevel with its protocol for being delete (closed) set to call an a method named on_close(). This additional method simply destroys the current window before quits the application's mainloop() causing it to terminate.
The first window—an instance of the TitleScreen class—is displayed automatically when an instance of the application class is created. This window has two Buttons one labelled Easy Mode and the other Hard Mode. When one of them is clicked, an instance of the appropriate Toplevel subclass is created after the current window is removed by it call its destroy() method.
mainmenu.py
import tkinter as tk
from tkinter.constants import *
from tkinter import font as tkfont
from basewin import BaseWin
from easymode import EasyApp
from hardmode import HardApp
class SampleApp(tk.Tk):
def __init__(self):
super().__init__()
self.title('Flag Quiz')
self.geometry('600x600')
self.resizable(FALSE, FALSE)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold")
self.withdraw() # Hide default root Tk window.
startpage = TitleScreen(self.master)
self.mainloop()
class TitleScreen(BaseWin):
def __init__(self, master):
super().__init__(master)
self.make_widgets()
def make_widgets(self):
label = tk.Label(self, text="This is the Start Page", font=self.master.title_font)
label.pack(side="top", fill="x", pady=10)
self.easy = tk.Button(self, text="Easy Mode", font=('default', 20),
command=self.play_easy)
self.hard = tk.Button(self, text="Easy Mode", font=('default', 20),
command=self.play_hard)
self.easy.pack()
self.hard.pack()
def play_easy(self):
self.destroy()
self.app = EasyApp(self.master)
def play_hard(self):
self.destroy()
self.app = HardApp(self.master)
if __name__ == '__main__':
SampleApp()
basewin.py
import tkinter as tk
from tkinter.constants import *
class BaseWin(tk.Toplevel):
def __init__(self, master):
super().__init__(master)
self.protocol("WM_DELETE_WINDOW", self.on_close)
def on_close(self):
self.destroy() # Destroy current window
self.master.quit() # Quit app.
easymode.py
import tkinter as tk
from tkinter.constants import *
from basewin import BaseWin
class EasyApp(BaseWin):
def __init__(self, master):
super().__init__(master)
self.title('Flag Quiz')
self.resizable(FALSE, FALSE)
self.make_widgets()
def make_widgets(self):
label = tk.Label(self, text="This is the Easy App", font=self.master.title_font)
label.pack(side="top", fill="x", pady=10)
hardmode.py
import tkinter as tk
from tkinter.constants import *
from basewin import BaseWin
class HardApp(BaseWin):
def __init__(self, master):
super().__init__(master)
self.title('Flag Quiz')
self.resizable(FALSE, FALSE)
self.make_widgets()
def make_widgets(self):
label = tk.Label(self, text="This is the Hard App", font=self.master.title_font)
label.pack(side="top", fill="x", pady=10)

How to set the maximum sash moves

Hi i've a code that look like this:
from tkinter import *
from tkinter import ttk
import socket, time, datetime
class UI:
def __init__(self):
self.root = Tk()
self.root.title("Chating App")
self.root.geometry("500x500")
def widgets(self):
self.m1 = PanedWindow(self.root, sashrelief=RAISED, width=10)
self.m1.pack(fill=BOTH, expand=1)
self.main_frame_1 = Frame(self.m1)
self.m1.add(self.main_frame_1)
Label(self.main_frame_1, text="hello worlds").pack()
self.m2 = PanedWindow(self.m1, orient=VERTICAL)
self.m1.add(self.m2)
self.label2 = Label(self.m2, text="top")
self.m2.add(self.label2)
def run(self):
self.widgets()
mainloop()
UI().run()
and my question is how can i set the maximum distances of the sash to be dragged?, so the user can drag the sash without fully shrinking the other pane. sorry if i misspelling :)
When you add item to PanedWindow then you can set its minimal size
self.m1.add(..., minsize=100)
If you use horizontal orientation then it will be used as minimal width.
If you use vertical orientation then it will be used as minimal height.
Documentation: PanedWindow
Working code:
import tkinter as tk # PEP8: `import *` is not preferred
from tkinter import ttk
class UI:
def __init__(self):
self.root = tk.Tk()
self.root.title("Chating App")
self.root.geometry("500x500")
def widgets(self):
self.m1 = tk.PanedWindow(self.root, width=10, sashrelief='raised')
self.m1.pack(fill='both', expand=True)
self.main_frame_1 = tk.Frame(self.m1)
self.m1.add(self.main_frame_1, minsize=100)
self.label_hello = tk.Label(self.main_frame_1, text="hello worlds")
self.label_hello.pack()
self.m2 = tk.PanedWindow(self.m1, orient='vertical', sashrelief='raised')
self.m1.add(self.m2, minsize=100)
self.label_top = tk.Label(self.m2, text="top")
self.m2.add(self.label_top, minsize=100)
self.label_bottom = tk.Label(self.m2, text="bottom")
self.m2.add(self.label_bottom, minsize=100)
def run(self):
self.widgets()
self.root.mainloop()
UI().run()
PEP 8 -- Style Guide for Python Code

I can't create a second window using tkinter, on os x

When creating a second window using python 3.6 and tkinter, it is not responsible. I`m using os x 10.11.6.
In other systems such as Ubuntu, this code works.
from tkinter import *
class win2:
def __init__(self):
self.root = Tk()
self.root.mainloop()
class win1:
def __init__(self):
self.root = Tk()
self.button = Button(self.root)
self.button.bind('<Button-1>', self.buttonFunc)
self.button.pack()
self.root.mainloop()
def buttonFunc(self, event):
windows2 = win2()
if __name__ == "__main__":
window1 = win1()
It's a very bad idea to use Tk() more than once in your program. Use it to make the root window, and then use Toplevel() to make any additional windows.
def buttonFunc(self, event):
Toplevel(self.root)
That said, it still looks like you are trying to do something the hard way. Can you describe better what your end goal is?
To make a modal window (a popup) use code like this:
try: #python3 imports
import tkinter as tk
except ImportError: #python3 failed, try python2 imports
import Tkinter as tk
class Main(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
lbl = tk.Label(self, text="this is the main frame")
lbl.pack()
btn = tk.Button(self, text='click me', command=self.open_popup)
btn.pack()
def open_popup(self):
print("runs before the popup")
Popup(self)
print("runs after the popup closes")
class Popup(tk.Toplevel):
"""modal window requires a master"""
def __init__(self, master, **kwargs):
tk.Toplevel.__init__(self, master, **kwargs)
lbl = tk.Label(self, text="this is the popup")
lbl.pack()
btn = tk.Button(self, text="OK", command=self.destroy)
btn.pack()
# The following commands keep the popup on top.
# Remove these if you want a program with 2 responding windows.
# These commands must be at the end of __init__
self.transient(master) # set to be on top of the main window
self.grab_set() # hijack all commands from the master (clicks on the main window are ignored)
master.wait_window(self) # pause anything on the main window until this one closes
def main():
root = tk.Tk()
window = Main(root)
window.pack()
root.mainloop()
if __name__ == '__main__':
main()
This code works for me.
from tkinter import *
class win1:
def __init__(self):
root = Tk()
button = Button(root)
button.bind('<Button-1>', self.buttonFunc)
button.pack()
root.mainloop()
def buttonFunc(self, event):
window2 = win2()
class win2(win1):
def __init__(self):
top = Toplevel()
if __name__ == "__main__":
window1 = win1()

Python 2.7: updating Tkinter Label widget content

I'm trying to make my Tkinter Label widget update but, where I thought it was straightforward, now I can't sort it out.
My code is:
import Tkinter as tk
import json, htmllib, formatter, urllib2
from http_dict import http_status_dict
from urllib2 import *
from contextlib import closing
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets(self):
StatusTextVar = tk.StringVar()
self.EntryText = tk.Entry(self)
self.GetButton = tk.Button(self, command=self.GetURL)
self.StatusLabel = tk.Label(self, textvariable=StatusTextVar)
self.EntryText.grid(row=0, column=0)
self.GetButton.grid(row=0, column=1, sticky=tk.E)
self.StatusLabel.grid(row=1, column=0, sticky=tk.W)
def GetURL(self):
try:
self.url_target = ("http://www." + self.EntryText.get())
self.req = urllib2.urlopen(self.url_target)
StatusTextVar = "Success"
except:
self.StatusTextVar = "Wrong input. Retry"
pass
app = Application()
app.mainloop()
I've tried several ways but either the Label won't update, or the interpreter raises errors.
Note: In the excerpt I deleted as much as code as possible to avoid confusion.
You need to use the StringVar set method to change the label text. Also:
StatusTextVar = "Success"
is not referencing self and will not change any state.
You should first change all StatusTextVar to self.StatusTextVar and then update the set calls:
self.StatusTextVar = "Success"
self.StatusTextVar = "Wrong input. Retry"
to
self.StatusTextVar.set("Success")
self.StatusTextVar.set("Wrong input. Retry")
Updating all StatusTextVar instances and using the set method, I get:
import Tkinter as tk
import json, htmllib, formatter, urllib2
from urllib2 import *
from contextlib import closing
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets(self):
self.StatusTextVar = tk.StringVar()
self.EntryText = tk.Entry(self)
self.GetButton = tk.Button(self, command=self.GetURL)
self.StatusLabel = tk.Label(self, textvariable=self.StatusTextVar)
self.EntryText.grid(row=0, column=0)
self.GetButton.grid(row=0, column=1, sticky=tk.E)
self.StatusLabel.grid(row=1, column=0, sticky=tk.W)
def GetURL(self):
try:
self.url_target = ("http://www." + self.EntryText.get())
self.req = urllib2.urlopen(self.url_target)
self.StatusTextVar.set("Success")
except:
self.StatusTextVar.set("Wrong input. Retry")
pass
root = tk.Tk()
app = Application(master=root)
app.mainloop()
It works as one would expect.

Categories

Resources