I have a main program window with a frame and a menu for invoking calculation modules.
from tkinter import Menu, Label, Tk, Frame, Scrollbar, Canvas, N, E, S
import runpy
import Bolt_connection
from importlib import reload
# Program window dimensions
root = Tk()
root.title("Name")
root.geometry("1260x700")
root.update()
MaxX = root.winfo_width()
MaxY = root.winfo_height()
canvas = Canvas(root, width=MaxX, height=MaxY, bg="white")
scroll_y = Scrollbar(root, orient="vertical", command=canvas.yview)
frame = Frame(canvas)
for i in range(50):
Label(frame).grid()
i += 1
canvas.create_window(0, 0, anchor='nw', window=frame)
canvas.update_idletasks()
canvas.configure(scrollregion=canvas.bbox('all'),
yscrollcommand=scroll_y.set)
canvas.grid()
scroll_y.grid(row=0, sticky=E + N + S)
main_menu = Menu()
# Submenu for Export to...
file_menu = Menu(tearoff=0)
help_menu = Menu(file_menu, tearoff=0)
help_menu_export_to = Menu(help_menu, tearoff=0)
help_menu_export_to.add_command(label="Excel")
help_menu_export_to.add_command(label="Word")
def start_bolt_connection():
import Bolt_connection
def start_key_connection():
import Key_connection
# Submenu for Part calculation selection
calculation_selection_menu = Menu(tearoff=0)
help_menu2 = Menu(calculation_selection_menu, tearoff=0)
help_menu2_part_calculation_selection = Menu(help_menu2, tearoff=0)
B2 = help_menu2_part_calculation_selection.add_command(label="Bolted (screw) connection", command=start_bolt_connection)
help_menu2_part_calculation_selection.add_command(label="Key connection", command=start_key_connection)
help_menu2_part_calculation_selection.add_command(label="Pinned connection")
# File menu
file_menu.add_command(label="New")
file_menu.add_command(label="Save")
file_menu.add_cascade(label="Export to...", menu=help_menu_export_to)
file_menu.add_command(label="Open")
file_menu.add_command(label="Exit")
# Main menu
main_menu.add_cascade(label="File", menu=file_menu)
main_menu.add_cascade(label="About")
main_menu.add_cascade(label="Help")
main_menu.add_cascade(label="Part calculation selection", menu=help_menu2_part_calculation_selection)
runpy.run_module('Bolt_connection')
root.config(menu=main_menu)
root.mainloop()
I want to see a window that looks like this when the program starts. Then, when you click on one of the menu buttons (for example, Key connection), the frame should update and display the graphical interface of the new module. After clicking the window should look like this.
The problem is that when the graphic part of the new module is displayed, the graphic part of the old module is not erased and they overlap each other. How to make the program delete the graphic part of the old module? The grid_remove() and reload() functions do not help.
An additional explanation of what I want to get when I run the program.
Program starts.
The main window appears with the calculation module already running, installed by default. In this case, "Bolt connection". The window should now look like this.
The user selects one of the calculation modules from the menu. In this case, "Key connection". The graphic part of the previous module is erased, and the new module is displayed. The window should now look like this.
UPD
For a better understanding of the problem, add a link to google drive where the project files are located.
https://drive.google.com/drive/folders/110OrRqlfzGmswg8cGHO3-C4VxfRj1sos?usp=sharing
In this folder there are two txt files with the code of the exported modules, so that you do not have to download the project to your computer and run it .
main.py
import tkinter as tk
import Mod1
import Mod2
root = tk.Tk()
m1 = Mod1.Model(root)
m2 = Mod2.Model(root)
m1.grid(column= 0, row=0)
m2.grid(column = 0 ,row=0)
def callback():
m1.lift()
b = tk.Button(text='click me', command=callback)
b.grid(column=0,row=1)
Mod1.py
from __main__ import tk
class Model(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.configure(bg="red", width=300, height=300)
Mod2.py
from __main__ import tk
class Model(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.configure(bg="blue", width=300, height=300)
Explaination
In your Modules you define your Model's as a subclass of tk.Frame, that gives you the ability to handle your Models as same as a tk.Frame.
Related
I have programmed a 2600 lines application which worked great when running from the IDE. Now I have created an executable via Pyinstaller and now the GUI does not start. The application starts and disappears quickly. I do not get any errors (anymore, solved them), however this problem remains. I think it has to do with missing the mainloop() in my application, which I don't know how to apply in this particular case. Usually its like this:
root = tk.Tk()
root.mainloop()
In my case I created a class for my window adding a menubar and label as statusbar (the latter not shown in my code below). This makes me assigning this class being a Tk() to main_window. Where do I put the mainloop() without getting an error?
I already tried:
main_window.mainloop()
since main_window is the window where all frames put on to, but then I get the following error in the IDE:
main_window.mainloop() AttributeError: 'AppWindow' object has no attribute 'mainloop'
How do I apply the mainloop() into my application without getting the above mentioned error? Or how do I get my GUI to be working in a different manner? Both answers are welcome.
Here is the necessary code to know:
import tkinter as tk
class AppWindow():
def __init__(self, master):
self.master = master
master.title("Basic Application")
master.geometry("1060x680")
master.grid_propagate(False)
#create drop down menu
self.menubar = tk.Menu(master) # main menubar
#Add filemenu
self.filemenu = tk.Menu(self.menubar, tearoff=0) #sub menu
self.filemenu.add_separator() #create a bar in the menu
self.filemenu.add_command(label="Quit", command=master.destroy) #Add submenu item
self.menubar.add_cascade(label="File", menu=self.filemenu) #Add submenu to menubar
self.master.config(menu=self.menubar) #Show menu
class FrameOne(tk.Frame):
def __init__(self, parent):
super().__init__()
self["borderwidth"]=5
self["relief"]="ridge"
self.create_widgets() #Function which creates all widgets
self.position_widgets() #Function which position all widgets
def create_widgets(self): #Function which creates all widgets
pass
def position_widgets(self): #Function which position all widgets
pass
#Create a window as defined in the AppWindow class
main_window = AppWindow(tk.Tk())
#Create a Frame as defined in class FrameOne
first_frame = FrameOne(main_window)
first_frame.grid(row=0, column=0) #Positioning Frame on Window
main_window.mainloop() #THIS PROVIDES AN ERROR | GUI DOES NOT START WITHOUT
mainloop is a method on the tkinter root window and on tkinter itself. Like the error says, it's not a method of your AppWindow class.
In your case you should do it like this:
root = tk.Tk()
main_window = AppWindow(root)
root.mainloop()
I am having a big issue. The Canvas loads perfectly but the image does not display.
I started Python 1 week ago and I have no clue why does is not working. Can anyone please show me the way to solve the issue of the image not loading on the canvas?
from Tkinter import *
from PIL import ImageTk
from PIL import Image
class Fake_Virus:
def __init__(self, master):
self.master = master
master.title("Totally not a virus!")
b = Button(master, text="Help", command=self.prank)
b.pack(padx=10, pady=10, side=LEFT)
quit = Button(master, text="Close", command=self.close_window)
quit.pack(padx=10, pady=10, side=RIGHT)
photo = PhotoImage("eh.gif")
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
f = Frame(master, height=150, width=150)
f.pack_propagate(0) # don't shrink
f.pack()
def prank(self):
print "work"
return
def close_window(self):
root.destroy()
return
root = Tk()
my_gui = Fake_Virus(root)
root.mainloop()
You should use the file option to initialize the photo image object.
This means you need to change photo = PhotoImage("eh.gif") to photo = PhotoImage(file="eh.gif")
Now your code will work. But a working code is not necessarily a good code. There are other issues with your code. Let me go through them quickly:
It is better to code import Tkinter as Tk than from Tkinter import *
Why that hyphen in your class name? Follow PEP8 so that, in the futur, people will find it easy to review and understand your code.
Good that you have written self.master = master (read complete code to know why) but then you have never used it. This means you made a good decision and you render it useless.
You set the title of the window within the initializer. It is better if you do that in a separate function so that whenever you want to add additional settings to your GUI (such as the size, font or whatever) you will only add code to that function instead of vomiting lot of trash inside the initializer which rather needs to be clean.
None of the widgets you created is 'selfed' (you may read Why explicit self has to stay)
It is better you create the widgets in a separate function otherwise your __init__() will be dirty.
Why do you use return in prank() and close_window()? By default, Python functions that do not return something return None anyway so it is useless to code that.
Why did you pack one button to left and the other one to right and then no pack siding for the label? Read about the pack() geometry manager.
Why you did not attach the label to a parent widget as you did for the 2 other buttons? All Tkinter widgets need to be clung into a parent widget. The grand parent of those widgets is an instance of Tkinter.Tk()
Why did you create that frame and then you never used it? You are not doing anything with it, so ..?
Given these remarks, I want to provide you an improved -but not perfect- version of your program. You can then follow this 'philosophy' to add or modifying existing widgets:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import Tkinter as Tk
from PIL import ImageTk
class FakeVirus:
def __init__(self, master):
self.master = master
self.configure_gui()
self.create_widgets()
def configure_gui(self):
self.master.title('Totally not a virus!')
def create_widgets(self):
self.create_buttons()
self.create_label_for_image()
def create_buttons(self):
self.help = Tk.Button(self.master, text='Help', command=self.prank)
self.help.pack(side=Tk.LEFT)
self.quit = Tk.Button(self.master, text='Close', command=self.close_window)
self.quit.pack(side=Tk.LEFT)
def create_label_for_image(self):
self.image_label = Tk.Label(self.master)
self.image_label.pack(side=Tk.LEFT)
self.load_image_to_label()
def load_image_to_label(self):
self.photo = ImageTk.PhotoImage(file='eh.gif')
self.image_label.image = self.photo
self.image_label.config(image=self.photo)
def prank(self):
print "work"
def close_window(self):
root.destroy()
if __name__ == '__main__':
root = Tk.Tk()
my_gui = FakeVirus(root)
root.mainloop()
The output of the above program is:
So for some reason the scale function in tkinter doesn't want to output the number on the scale. All i receive is either 0.0 or nothing. It seems to be to do with the GUI and calling functions through the GUI. Written and run in python 3.4.
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
iterations=30
def settings():
global itervar, iterscale
sGui = Tk()
itervar = DoubleVar()
iterscale = Scale(sGui, orient="horizontal", from_=1, to=1000, variable=itervar)
iterscale.pack()
iterbutton = Button(sGui, text="Save Settings", command=saveSettings)
iterbutton.pack()
sGui.mainloop()
def saveSettings():
global iterations
iterations = itervar.get()
print(iterations)
def doNothing():
pass
def main():
global root, version
root= Tk()
menu = Menu(root)
root.config(menu=menu)
fileMenu = Menu(menu)
menu.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="Quit", command=quit)
benchmarkMenu = Menu(menu)
menu.add_cascade(label="Benchmark", menu=benchmarkMenu)
benchmarkMenu.add_command(label="Run [All]", command=doNothing)
benchmarkMenu.add_separator()
benchmarkMenu.add_command(label="Settings", command=settings)
root.mainloop()
#Main
main()
I have tried the functions settings and saveSettings on their own and they work fine, but when i call it through the GUI it doesn't seem to work.
Any ideas on the problem, my only solution would be have the settings function and saveSettings function in a different file and then run that file externally with os.startfile("etc...")
Minimal fix: change this
itervar = DoubleVar()
to this:
itervar = DoubleVar(sGui)
Because you have two root applications (root and sGui are both instances of Tk) the implied parent widget for itervar is the first one created, being root so tkinter gets confused when you specify it as the variable for a completely different application.
But I would highly recommend using a Toplevel instance to keep the windows a part of the same program:
sGui = Toplevel(root)
...
#sGui.mainloop() #no longer need this
although if you want to be able to run the setting window without the main one you might consider making all your visible windows Toplevels and make the actual root hidden:
# I'm not sure if you want to call it this
abs_root = Tk() # but you are already using root
abs_root.withdraw() #hide the window
Then make root = Toplevel(abs_root)
You coud phase out the variable all together by using .geting the scale directly:
iterations = iterscale.get()
I have code for selecting backup that should be loaded. It opens Toplevel window and lets you select one of the backups to load. When this window opens, I would like to block input to original window, so the only way to get back to original window is by closing the new Toplevel window.
The part of code that I hoped would work:
from tkinter import *
class BackupsGui:
def __init__(self, parent):
top = Toplevel()
self.top = top
Some more code and __init__ ending with:
top.update_idletasks()
top.overrideredirect(True)
top.mainloop()
or:
top.transient(parent)
top.mainloop()
Niether code part appears to change Toplevel interaction in any way, nor does changing if top.mainloop() precedes top.transient() or top.update_idletasks().
What do I miss?
transient and overrideredirect have nothing to do with event handling. If you want to block all input except for the toplevel, you need to call grab_set on the toplevel window. This will cause all events to be sent to that window.
Run the following code, and notice that if you don't check the box, you can continue to create new windows and change the value of the checkbox. Once checked, the next window grabs all events, preventing you from interacting with the other windows.
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, root):
tk.Frame.__init__(self, root)
self.do_grab = tk.BooleanVar()
cb = tk.Checkbutton(self, text="New window grabs all events",
variable=self.do_grab, onvalue=True, offvalue=False)
cb.pack()
new_button = tk.Button(self, text="New window", command=self.on_click)
new_button.pack()
def on_click(self):
self.top = tk.Toplevel(self)
button = tk.Button(self.top, text="dismiss", command=self.top.destroy)
do_grab = self.do_grab.get()
if do_grab:
label = tk.Label(self.top, wraplength=200,
text="This window grabs all events")
else:
label = tk.Label(self.top, wraplength = 200,
text="This window does NOT grab all events")
label.pack(fill="x")
button.pack()
if do_grab:
self.top.grab_set()
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
I am using Tkinter to build two windows. One the main one, pressing a button leads to the creation of the second window.
This second window does not get focus immediately when it created. That I am able to fix by calling .focus_force(). However, when I call the askdirectory() function from tkFileDialog, the focus changes back to the first window.
How can I prevent that focus switch from happening, without simply calling focus_force() all over the place?
To replicate problem:
from Tkinter import *
from tkFileDialog import *
class app:
def __init__(self, master):
Button(master, command = make_new).grid()
def make_new(self):
root = Tk()
new = new_win(root)
root.mainloop() #here the focus is on the first window
class new_win:
def __init__(self, master):
f = askdirectory() #even after placing focus on second window,
#focus goes back to first window here
I am using Python 2.7.3. Thanks!
the little-documented wm_attributes method might help:
from Tkinter import *
import tkFileDialog
root = Tk()
top = Toplevel()
top.wm_attributes('-topmost', 1)
top.withdraw()
top.protocol('WM_DELETE_WINDOW', top.withdraw)
def do_dialog():
oldFoc = top.focus_get()
print tkFileDialog.askdirectory()
if oldFoc: oldFoc.focus_set()
b0 = Button(top, text='choose dir', command=do_dialog)
b0.pack(padx=100, pady=100)
def popup():
top.deiconify()
b0.focus_set()
b1 = Button(root, text='popup', command=popup)
b1.pack(padx=100, pady=100)
root.mainloop()