Tkinter blank window - python

I found this introductory tutorial online, but when I run it, I get just a blank window. Any idea what's going wrong?
# A more complex example showing the use of classes in GUI programming
from tkinter import *
class GUIExample:
def __init__(self, master):
self.master = master # for showInfo()
# Create frame to hold widgets
frame = Frame(master)
# Create label for header
self.headLbl = Label(frame, text="Widget Demo Program", relief=RIDGE)
self.headLbl.pack(side=TOP, fill=X)
# Dummy frame for border
spacerFrame = Frame(frame, borderwidth=10)
# Create frame to hold center part of the form
centerFrame = Frame(spacerFrame)
leftColumn = Frame(centerFrame, relief=GROOVE, borderwidth=10)
rightColumn = Frame(centerFrame, relief=GROOVE, borderwidth=10)
# Some colorful widgets
self.colorLabel = Label(rightColumn, text="Select a color")
self.colorLabel.pack(expand=YES, fill=X)
entryText = StringVar(master)
entryText.set("Select a color")
self.colorEntry = Entry(rightColumn, textvariable=entryText)
self.colorEntry.pack(expand=YES, fill=X)
# Create some radio buttons
self.radioBtns = []
self.radioVal = StringVar(master)
btnList = ("black", "red", "green", "blue", "white", "yellow")
for color in btnList:
self.radioBtns.append(Radiobutton(leftColumn, text=color, value=color, \
indicatoron=TRUE, variable=self.radioVal, command=self.updateColor))
else:
if (len(btnList) > 0):
self.radioVal.set(btnList[0])
self.updateColor()
for btn in self.radioBtns:
btn.pack(anchor=W)
# Make the frames visible
leftColumn.pack(side=LEFT, expand=YES, fill=Y)
rightColumn.pack(side=LEFT, expand=YES, fill=BOTH)
centerFrame.pack(side=TOP, expand=YES, fill=BOTH)
# Create an indicator checkbutton
self.indicVal = BooleanVar(master)
self.indicVal.set(TRUE)
self.updateIndic()
Checkbutton(spacerFrame, text="Show indicator", command=self.updateIndic, \
variable=self.indicVal).pack(side=TOP, fill=X)
# Create the Info button
Button(spacerFrame, text="Info", command=self.showInfo).pack(side=TOP, fill=X)
# Create the Quit button
Button(spacerFrame, text="Quit", command=self.quit).pack(side=TOP, fill=X)
def quit(self):
import sys
sys.exit()
def updateColor(self):
self.colorLabel.configure(fg=self.radioVal.get())
self.colorEntry.configure(fg=self.radioVal.get())
def updateIndic(self):
for btn in self.radioBtns:
btn.configure(indicatoron=self.indicVal.get())
def updateColorPrev(self):
if (self.colorprevVal.get()):
for btn in self.radioBtns:
color = btn.cget("text")
btn.configure(fg=color)
else:
for btn in self.radioBtns:
btn.configure(fg="black")
def showInfo(self):
toplevel = Toplevel(self.master, bg="white")
toplevel.transient = self.master
toplevel.title("Program info")
Label(toplevel, text="A simple Tkinter demo", fg="navy", bg="white").pack(pady=20)
Label(toplevel, text="Written by Bruno Dufour", bg = "white").pack()
Label(toplevel, text="http://www.cs.mcgill.ca/ ̃bdufou1/", bg="white").pack()
Button(toplevel, text="Close", command=toplevel.withdraw).pack(pady=30)
root = Tk()
ex = GUIExample(root)
root.title("A simple widget demo")
root.mainloop()

They forgot
frame.pack()
and
spacerFrame.pack()
I didn't test rest of code.
EDIT: BTW: In place of
def quit(self):
import sys
sys.exit()
I would use something more natural - and less drastic
def quit(self):
self.master.destroy()

Related

Make the scrollbar automatically scroll back up in tkinter

I have an interface made with tkinter and it has many scrollable frames, where the user can press a button and each button will show the corresponding frame (and removes the previously shown frame).
When changing from a frame to another and back to the first frame the scrollbar stays in it's previous place. Is there a way to automatically make the scrollbar scroll back up when changing from a frame to another?
here's my code:
import tkinter as tk
from tkinter import *
from tkinter import ttk
import platform
# ++++++++++++++++++++++++++++++++++
# Custom Class for Scrollable Frames
# ++++++++++++++++++++++++++++++++++
class ScrollableFrame(tk.Frame):
def onFrameConfigure(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def onCanvasConfigure(self, event):
canvas_width = event.width
self.canvas.itemconfig(self.canvas_window, width=canvas_width)
def onMouseWheel(self, event):
if platform.system() == 'Windows':
self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
else:
if event.num == 4:
self.canvas.yview_scroll(-1, "units")
elif event.num == 5:
self.canvas.yview_scroll(1, "units")
def onEnter(self, event):
if platform.system() == 'Linux':
self.canvas.bind_all("<Button-4>", self.onMouseWheel)
self.canvas.bind_all("<Button-5>", self.onMouseWheel)
else:
self.canvas.bind_all("<MouseWheel>", self.onMouseWheel)
def onLeave(self, event):
if platform.system() == 'Linux':
self.canvas.unbind_all("<Button-4>")
self.canvas.unbind_all("<Button-5>")
else:
self.canvas.unbind_all("<MouseWheel>")
def __init__(self, parent):
super().__init__(parent) # create a frame (self)
self.canvas = tk.Canvas(self, borderwidth=0, height=canvas_height, width=canvas_width, background="white")
self.viewPort = tk.Frame(self.canvas, background="white")
self.vsb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview, background="white")
self.canvas.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(side="right", fill="y")
self.canvas.pack(side="left", fill="both", expand=True)
self.canvas_window = self.canvas.create_window((4, 4), window=self.viewPort, anchor="nw", tags="self.viewPort")
self.canvas.bind("<Configure>", self.onCanvasConfigure)
self.viewPort.bind("<Configure>", self.onFrameConfigure)
self.viewPort.bind('<Enter>', self.onEnter)
self.viewPort.bind('<Leave>', self.onLeave)
self.onFrameConfigure(None)
# ----- resets all frames -----
def reset():
update_frame.pack_forget()
home_frame.pack_forget()
# ----- Custom Side Menu Buttons -----
def menubttn(x, y, text, cmd):
def on_entera(e):
myButton1['background'] = bcolor
def on_leavea(e):
myButton1['background'] = fcolor
myButton1 = Button(sidemenu, text=text,
width=15,
height=2,
border=0,
bg=fcolor,
activebackground=bcolor,
command=cmd)
myButton1.bind("<Enter>", on_entera)
myButton1.bind("<Leave>", on_leavea)
myButton1.place(x=x, y=y)
# ----- helper function to insert entry boxes on frames -----
def entrybox(frame, index):
entry_box = Entry(frame,width=50)
entry_box.grid(row=index, column=1, pady=5, padx=(0, 100))
return entry_box
# ++++++++++++++++++++++++++++++++++
# functions that handle frames
# ++++++++++++++++++++++++++++++++++
# ----- Handles homepage -----
def homepage():
reset()
home_frame.pack()
# ----- Handles update frame -----
def update():
reset()
update_frame.pack()
def delete():
homepage()
update_lf.pack_forget()
def edit(self):
if(dropdown_menu.get() != "choose"):
update_lf.pack()
entry_boxes = []
for i in range(15):
Label(update_lf, text="name", background="white").grid(row=i, column=0, sticky=W, padx=(100, 20))
entry_boxes.append(entrybox(update_lf, i))
delete_button = Button(update_lf, text="delete", command=delete)
delete_button.grid(row=i+1, column=1, columnspan=2)
else:
update_lf.pack_forget()
dropdown_menu.pack()
dropdown_menu.bind("<<ComboboxSelected>>", edit)
# +++++++++++++++
# Initializations
# +++++++++++++++
bcolor = '#77B9CF'
fcolor = '#D5E2EB'
frame_width = 900
frame_height = 500
sidemenu_width = 111
canvas_width = frame_width - sidemenu_width - 24
canvas_height = frame_height - 40
canvas_height_scroll = canvas_height - 85
root = Tk()
root.geometry(f'{frame_width}x{frame_height}')
root.configure(bg='white')
root.resizable(False, False)
root.title("test")
# +++++++++++++
# Create Frames
# +++++++++++++
# ----- main projects frame -----
projects_frame = Frame(root, height=frame_height, width=frame_width - sidemenu_width, bg='white')
projects_frame.place(x=sidemenu_width, y=0)
# ----- sidemenu frame -----
sidemenu = Frame(root, width=sidemenu_width, height=frame_height, bg='#D5E2EB')
sidemenu.place(x=0, y=0)
# ----- homepage frame -----
home_frame = Frame(projects_frame, height=frame_height, width=frame_width - sidemenu_width, bg='white')
home_frame.pack()
Label(home_frame, text="WELCOME!", background="white", font=("", 40), foreground=bcolor).place(relx=0.5, rely=0.3,
anchor=CENTER)
Label(home_frame, text="this is the homepage", background="white", font=("", 20), foreground=bcolor).place(relx=0.5, rely=0.4,
anchor=CENTER)
# ----- update frame -----
menu =["elem1","elem2","elem3"]
update_frame = ScrollableFrame(projects_frame)
update_lf = LabelFrame(update_frame.viewPort, text="frame", padx=10, pady=10, background="white")
dropdown_menu = ttk.Combobox(update_frame.viewPort, state="readonly",
values=["choose"] + menu, width=55)
dropdown_menu.current(0)
# ++++++++++++++++++++++++
# Create Side Menu Buttons
# ++++++++++++++++++++++++
menubttn(0, 100, 'HOMEPAGE', homepage)
menubttn(0, 200, 'UPDATE', update)
root.mainloop()
The problem happens when I press the delete button in the update frame and go back to the update frame.. and I assume that it's because the frame is scrolled down but I might be wrong..
It's hard to help without knowing what you've already tried - please post a Minimal Reproducible Example
That said, I believe you can accomplish this by binding an event to your scrollable widgets.
# I don't know what your widgets are called, so I called it 'scrollable_frame' here
scrollable_frame.bind(
'<FocusOut>', # whenever the widget loses focus...
lambda _event: scrollable_frame.yview_moveto(0) # scroll to top
)
You'll need to bind a similar event to each of your scrollable frames separately.
In order to ensure the frame you just scrolled has focus (so you can properly track when it loses focus, you may want to add another event binding to each frame like so
scrollable_frame.bind(
'<MouseWheel>', # when scrolling with the mouse wheel...
lambda _event: self.scrollable_frame.focus_force() # force focus
)
The story is slightly different if you're scrolling with a scrollbar, but the idea is the same in principle.
I can edit my answer to be more specific to your situation once you post your code.

How can I return a variable from a function that is opening a file using filedialog after selecting a tkinter button?

All of the tutorials I have seen deomonstrate the tkinter filedialog.askopenfilename function by only using the information collected within the function that is linked to the tkinter button. I can pass information in the function, but I would like to pass variables (filepath, images, etc.) outside the function and have them update variables in my GUI.
I have commented out the location I would like to call the variables in main_gui_setup function below. Any help will be appreciated, as it has been very demoralizing not being able to open a file. If this problem persists, my future as a programmer may be limited to creating tic-tac-toe games or instructional videos for Youtube.
from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog, messagebox
from PIL import ImageTk, Image # was import PIL.Image, PIL.ImageTk
import cv2
def main():
root = Tk()
window1 = Window(root, "X-ray Assist", "Give up")
return None
# can't pass by reference in python
class Window():
n = 0
file_path = ""
img1_info = ""
def __init__(self, root, title, message):
self.root = root
self.root.title(title)
#self.root.geometry(geometry)
self.screen_width = root.winfo_screenwidth()
self.screen_height = root.winfo_screenheight()
#self.root.attributes('-topmost', 1)
# SET APP WINDOW SIZE
scr_size_main = self.scr_size() # create instance of scr_size
self.root.geometry("%dx%d+%d+%d" % (self.root_width, self.root_height, self.root_x, self.root_y))
# CREATE MAIN WINDOW GUI
create_gui = self.main_gui_setup()
self.root.mainloop()
pass
def scr_size(self):
'''Reads monitor size and adjusts GUI frame sizes'''
self.root_width = int(self.screen_width*0.52)
self.root_height = int(self.screen_height*0.9)
self.root_x = int(self.screen_width*0.23)
self.root_y = int(self.screen_height*0.02)
self.img_ht_full = int(self.screen_height*0.82)
self.tools_nb_width = int(self.screen_width*0.22)
self.tools_nb_height = int(self.screen_height*0.48)
self.hist_nb_width = int(self.screen_width*0.22)
self.hist_nb_height = int(self.screen_height*0.23)
def open_image(self):
main_win = ttk.Frame(self.root)
main_win.grid(column=0, row=0)
self.file_path = filedialog.askopenfilename(initialdir='/', title='Open File',
filetypes=(('tif files', '*.tif'), ('all files', '*.*')))
self.file_path_label = ttk.Label(main_win, text=self.file_path)
self.file_path_label.grid(column=0, row=0, columnspan=1, sticky="nw", padx=(5,0), pady=1)
self.img1_8bit = cv2.imread(self.file_path, 0) #, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_GRAYSCALE)
#self.img1_8bit_resize = cv2.resize(self.img1_8bit, (self.img_ht_full, self.img_ht_full)) #, interpolation = cv2.INTER_CUBIC)
#self.img1_height, self.img1_width = self.img1_8bit.shape # not resized for screen
#img1_info = text = f"{self.img1_height} {self.img1_8bit.dtype} {self.img1_16bit.dtype}"
#print(self.img1_width, " x ", self.img1_height, " bitdepth = ", self.img1_8bit.dtype)
#img1_info = ttk.Label
#print(f"{self.img1_height} {self.img1_width} {self.img1_8bit.dtype}")
#img1_info.grid(column=3, row=1, columnspan=1, sticky="w", padx=(5,0), pady=1)
#img = io.imread(main_win.filename) #scikit
self.img1_16bit = cv2.imread(self.file_path, cv2.IMREAD_ANYDEPTH | cv2.IMREAD_GRAYSCALE)
#self.img_canvas = tk.Canvas(self.root, width=self.img_ht_full, height=self.img_ht_full)
#self.img_canvas.grid(column=1, row=2, columnspan=10, rowspan=10, sticky="nw")
#self.img_canvas.image = ImageTk.PhotoImage(image=Image.fromarray(self.img1_8bit_resize))
#self.img_canvas.create_image(0,0, image=self.img_canvas.image, anchor="nw")
# .create_line(x1, y1, x2, y2, fill="color")
#self.img_canvas.create_line((self.img_ht_full/2), 0, (self.img_ht_full/2), (self.img_ht_full), fill="yellow")
#self.img_canvas.create_line(0, (self.img_ht_full/2), (self.img_ht_full), (self.img_ht_full/2), fill="yellow")
def main_gui_setup(self):
main_win = ttk.Frame(self.root)
main_win.grid(column=0, row=0)
image_win = ttk.Frame(main_win, borderwidth=25, relief="groove", width=self.img_ht_full, height=self.img_ht_full)
image_win.grid(column=1, row=2, columnspan=10, rowspan=10, sticky="nw")
toolbar = ttk.Frame(main_win, borderwidth=5) #, width=1100, height=15)
toolbar.grid(column=0, row=0, columnspan=10, rowspan=1, sticky="nw", padx=20)
hist_win = ttk.Frame(main_win, borderwidth=25, relief="groove", width=300, height=200)
panel_info = ttk.Label(main_win, text=f"{self.screen_width} x {self.screen_height}")
panel_info.grid(column=5, row=1, columnspan=1, sticky="e", pady=1)
# SCROLL SLIDER AT BOTTOM
slider = ttk.Scrollbar(main_win, orient="horizontal")
slider.grid(column=1, row=13, columnspan=7, padx=5, pady=5, sticky="ew")
#X-RAY AND DETECTOR SETTINGS - will input these from separate class
kv = ttk.Label(main_win, text="125kV")
kv.grid(column=0, row=2, columnspan=1, padx=15, pady=5)
file_path_label = ttk.Label(main_win, text="No image loaded")
file_path_label.grid(column=1, row=1, columnspan=1, sticky="nw", padx=(5,0), pady=1)
# CREATE BUTTONS
open = ttk.Button(toolbar, text="Open", width=10, command=self.open_image)
open.grid(column=0, row=0)
save = ttk.Button(toolbar, text="Save", width=10)
save.grid(column=1, row=0)
b1 = ttk.Button(toolbar, text="1", width=10)
b1.grid(column=2, row=0)
b2 = ttk.Button(toolbar, text="2", width=10)
b2.grid(column=3, row=0)
pass
main()
You aren't thinking of event driven programming correctly. In event driven programming you have callbacks to the functions you defined. Let's look at your code:
def get_path(self):
...
self.path_label = ...
...
def main_gui_setup(self):
main_win = ttk.Frame(self.root)
main_win.pack()
open = ttk.Button(main_win, text="Open", width=10, command=self.get_path)
open.pack()
# Problematic code:
# main_label = ttk.Label(main_win, self.path_label)
# main_label.pack()
When main_gui_setup is called it creates a frame and a button inside it. When the button is clicked it calls get_path which sets up the path_label variable. The problem that you were facing is that that as soon as you create your button (without waiting for the button to be pressed), you create the label called main_label.
For a simple fix to your problem try this:
def get_path(self):
...
self.file_path = ...
self.path_label = ...
...
def button_callback(self, main_win):
# set up
self.get_path()
# My guess is that you wanted `self.file_path` here instead of `self.path_label`
main_label = ttk.Label(main_win, self.file_path)
main_label.pack()
def main_gui_setup(self):
main_win = ttk.Frame(self.root)
main_win.pack()
# I am using a lambda and passing in `main_win` because you haven't
# assigned it to `self` using `self.main_win = ...`
open = ttk.Button(main_win, text="Open", width=10, command=lambda: self.button_callback(main_win))
open.pack()
I am still confused by what You are trying to accomplish:
from tkinter import Tk, Button, Label, filedialog
class MainWindow(Tk):
def __init__(self):
Tk.__init__(self)
self.open_file_btn = Button(self, text='Open', command=self.open_file)
self.open_file_btn.pack()
self.file_name = None
def open_file(self):
self.file_name = filedialog.askopenfilename()
Label(self, text=self.file_name).pack()
root = MainWindow()
root.mainloop()
I will explain what will happen here! (You can change the .askopenfilename() attributes obviously).
When the program opens the filedialog and You select a file, that file name will now get assigned to self.file_name and that variable can be used anywhere in the class.
also from what I have seen You should learn more about classes and PEP 8

Need to Add a Scroll Toolbar to FGCs LabelFrame (Tkinter)

Working on an internal app and trying to get a scrollbar to "FGCs" labelFrame only, in addition, I need to scale the frame to the app size.
I'll be happy if anyone could assist me in refactoring this and create the scrollbar.
I know that I need to create a canvas or something, but do not know how.
This is a first time for me with Tkinter.
from tkinter import *
import os, subprocess
from tkinter import ttk
managment = ["MAIN","NAV","OUTPUT","OUTPUTSPARE","GATEWAY","Sync1","Sync2"]
servers = ["recon01","recon02","recon03","recon04","recon05","recon06","recon07","recon08","recon09","recon10","recon11","recon12","render01","render02","storinator"]
FGCs =["fgc01","fgc02","fgc03","fgc04","fgc05","fgc06","fgc07","fgc08","fgc09","fgc10","fgc11","fgc12","fgc13","fgc14","fgc15","fgc16","fgc17","fgc18","fgc19","fgc20","fgc21","fgc22","fgc23","fgc24","fgc25","fgc26","fgc27","fgc28","fgc29","fgc30","fgc31","fgc32","fgc33","fgc34","fgc35","fgc36","fgc37","fgc38","fgcspare1","fgcspare2","fgcspare3","fgcspare4"]
tests = ["Network", "GPU", "Time", "Gidel", "Snapshot", "Disks"]
testbuttons = []
serverbuttons = []
managebuttons = []
fgcbuttons = []
class mainwindow:
global test
global testbuttons
global managment
global managebuttons
global FGCs
def __init__(self,master):
self.master = master
master.title("System Report Tool")
master.geometry("1000x500")
self.Tests = ttk.LabelFrame(root, text="Tests")
self.Tests.pack(expand="no",anchor=W,pady=20)
for test in tests:
testcheck = ttk.Checkbutton(self.Tests, text=test)
testcheck.pack(side=LEFT, anchor="n")
testbuttons.append(testcheck)
def select_tests():
for test in testbuttons:
test.invoke()
selecttests = ttk.Checkbutton(root, text="Select All",command=select_tests)
selecttests.place(x=260,y=16)
self.Managment = ttk.LabelFrame(root, text="Managment")
self.Managment.configure(width=10, height=20)
self.Managment.pack(expand="no",anchor=W)
for manage in managment:
managecheck = ttk.Checkbutton(self.Managment, text=manage)
managecheck.pack(side=TOP, anchor="w")
managebuttons.append(managecheck)
def select_manage():
for manage in managebuttons:
manage.invoke()
selectmanage = ttk.Checkbutton(self.Managment, text="Select All",command=select_manage)
selectmanage.pack()
self.FGCs = ttk.LabelFrame(root, text="FGCs")
self.FGCs.configure(width=10, height=20)
self.FGCs.place(x=120,y=80)
for fgc in FGCs:
fgccheck = ttk.Checkbutton(self.FGCs, text=fgc)
fgccheck.pack(side=TOP, anchor="w")
fgcbuttons.append(fgccheck)
def select_fgc():
for fgc in fgcbuttons:
fgc.invoke()
selectfgc = ttk.Checkbutton(self.FGCs, text="Select All",command=select_fgc)
selectfgc.pack()
root = Tk()
Window = mainwindow(root)
root.mainloop()
Thanks in advance.
Copy code with class ScrolledFrame from scrolled-frame-canvas
Create ScrolledFrame inside LabelFrame self.FGCs
self.sf = ScrolledFrame(self.FGCs)
self.sf.pack()
And then put widgets in inner element in ScrolledFrame instead of putting them in self.FGCs like
fgccheck = ttk.Checkbutton(self.sf.inner, text=fgc)
Working code
import os
import subprocess
import tkinter as tk
from tkinter import *
from tkinter import ttk
class ScrolledFrame(tk.Frame):
def __init__(self, parent, vertical=True, horizontal=False):
super().__init__(parent)
# canvas for inner frame
self._canvas = tk.Canvas(self)
self._canvas.grid(row=0, column=0, sticky='news') # changed
# create right scrollbar and connect to canvas Y
self._vertical_bar = tk.Scrollbar(self, orient='vertical', command=self._canvas.yview)
if vertical:
self._vertical_bar.grid(row=0, column=1, sticky='ns')
self._canvas.configure(yscrollcommand=self._vertical_bar.set)
# create bottom scrollbar and connect to canvas X
self._horizontal_bar = tk.Scrollbar(self, orient='horizontal', command=self._canvas.xview)
if horizontal:
self._horizontal_bar.grid(row=1, column=0, sticky='we')
self._canvas.configure(xscrollcommand=self._horizontal_bar.set)
# inner frame for widgets
self.inner = tk.Frame(self._canvas)
self._window = self._canvas.create_window((0, 0), window=self.inner, anchor='nw')
# autoresize inner frame
self.columnconfigure(0, weight=1) # changed
self.rowconfigure(0, weight=1) # changed
# resize when configure changed
self.inner.bind('<Configure>', self.resize)
# resize inner frame to canvas size
self.resize_width = False
self.resize_height = False
self._canvas.bind('<Configure>', self.inner_resize)
def resize(self, event=None):
self._canvas.configure(scrollregion=self._canvas.bbox('all'))
def inner_resize(self, event):
# resize inner frame to canvas size
if self.resize_width:
self._canvas.itemconfig(self._window, width=event.width)
if self.resize_height:
self._canvas.itemconfig(self._window, height=event.height)
managment = ["MAIN","NAV","OUTPUT","OUTPUTSPARE","GATEWAY","Sync1","Sync2"]
servers = ["recon01","recon02","recon03","recon04","recon05","recon06","recon07","recon08","recon09","recon10","recon11","recon12","render01","render02","storinator"]
FGCs =["fgc01","fgc02","fgc03","fgc04","fgc05","fgc06","fgc07","fgc08","fgc09","fgc10","fgc11","fgc12","fgc13","fgc14","fgc15","fgc16","fgc17","fgc18","fgc19","fgc20","fgc21","fgc22","fgc23","fgc24","fgc25","fgc26","fgc27","fgc28","fgc29","fgc30","fgc31","fgc32","fgc33","fgc34","fgc35","fgc36","fgc37","fgc38","fgcspare1","fgcspare2","fgcspare3","fgcspare4"]
tests = ["Network", "GPU", "Time", "Gidel", "Snapshot", "Disks"]
testbuttons = []
serverbuttons = []
managebuttons = []
fgcbuttons = []
class mainwindow:
global test
global testbuttons
global managment
global managebuttons
global FGCs
def __init__(self,master):
self.master = master
master.title("System Report Tool")
master.geometry("1000x500")
self.Tests = ttk.LabelFrame(root, text="Tests")
self.Tests.pack(expand="no", anchor=W, pady=20)
for test in tests:
testcheck = ttk.Checkbutton(self.Tests, text=test)
testcheck.pack(side=LEFT, anchor="n")
testbuttons.append(testcheck)
def select_tests():
for test in testbuttons:
test.invoke()
selecttests = ttk.Checkbutton(root, text="Select All",command=select_tests)
selecttests.place(x=260,y=16)
self.Managment = ttk.LabelFrame(root, text="Managment")
self.Managment.configure(width=10, height=20)
self.Managment.pack(expand="no",anchor=W)
for manage in managment:
managecheck = ttk.Checkbutton(self.Managment, text=manage)
managecheck.pack(side=TOP, anchor="w")
managebuttons.append(managecheck)
def select_manage():
for manage in managebuttons:
manage.invoke()
selectmanage = ttk.Checkbutton(self.Managment, text="Select All",command=select_manage)
selectmanage.pack()
self.FGCs = ttk.LabelFrame(root, text="FGCs")
self.FGCs.configure(width=10, height=20)
self.FGCs.place(x=120, y=80)
self.sf = ScrolledFrame(self.FGCs)
self.sf.pack()
for fgc in FGCs:
fgccheck = ttk.Checkbutton(self.sf.inner, text=fgc)
fgccheck.pack(side=TOP, anchor="w")
fgcbuttons.append(fgccheck)
def select_fgc():
for fgc in fgcbuttons:
fgc.invoke()
selectfgc = ttk.Checkbutton(self.sf.inner, text="Select All",command=select_fgc)
selectfgc.pack()
root = Tk()
Window = mainwindow(root)
root.mainloop()
EDIT: This code uses pack() with some options to resize widgets when window is resized
import os
import subprocess
import tkinter as tk
from tkinter import *
from tkinter import ttk
class ScrolledFrame(tk.Frame):
def __init__(self, parent, vertical=True, horizontal=False):
super().__init__(parent)
# canvas for inner frame
self._canvas = tk.Canvas(self)
self._canvas.grid(row=0, column=0, sticky='news') # changed
# create right scrollbar and connect to canvas Y
self._vertical_bar = tk.Scrollbar(self, orient='vertical', command=self._canvas.yview)
if vertical:
self._vertical_bar.grid(row=0, column=1, sticky='ns')
self._canvas.configure(yscrollcommand=self._vertical_bar.set)
# create bottom scrollbar and connect to canvas X
self._horizontal_bar = tk.Scrollbar(self, orient='horizontal', command=self._canvas.xview)
if horizontal:
self._horizontal_bar.grid(row=1, column=0, sticky='we')
self._canvas.configure(xscrollcommand=self._horizontal_bar.set)
# inner frame for widgets
self.inner = tk.Frame(self._canvas)
self._window = self._canvas.create_window((0, 0), window=self.inner, anchor='nw')
# autoresize inner frame
self.columnconfigure(0, weight=1) # changed
self.rowconfigure(0, weight=1) # changed
# resize when configure changed
self.inner.bind('<Configure>', self.resize)
# resize inner frame to canvas size
self.resize_width = False
self.resize_height = False
self._canvas.bind('<Configure>', self.inner_resize)
def resize(self, event=None):
self._canvas.configure(scrollregion=self._canvas.bbox('all'))
def inner_resize(self, event):
# resize inner frame to canvas size
if self.resize_width:
self._canvas.itemconfig(self._window, width=event.width)
if self.resize_height:
self._canvas.itemconfig(self._window, height=event.height)
managment = ["MAIN","NAV","OUTPUT","OUTPUTSPARE","GATEWAY","Sync1","Sync2"]
servers = ["recon01","recon02","recon03","recon04","recon05","recon06","recon07","recon08","recon09","recon10","recon11","recon12","render01","render02","storinator"]
FGCs =["fgc01","fgc02","fgc03","fgc04","fgc05","fgc06","fgc07","fgc08","fgc09","fgc10","fgc11","fgc12","fgc13","fgc14","fgc15","fgc16","fgc17","fgc18","fgc19","fgc20","fgc21","fgc22","fgc23","fgc24","fgc25","fgc26","fgc27","fgc28","fgc29","fgc30","fgc31","fgc32","fgc33","fgc34","fgc35","fgc36","fgc37","fgc38","fgcspare1","fgcspare2","fgcspare3","fgcspare4"]
tests = ["Network", "GPU", "Time", "Gidel", "Snapshot", "Disks"]
testbuttons = []
serverbuttons = []
managebuttons = []
fgcbuttons = []
class mainwindow:
global test
global testbuttons
global managment
global managebuttons
global FGCs
def __init__(self,master):
self.master = master
master.title("System Report Tool")
master.geometry("1000x500")
# --- top ---
self.Tests = ttk.LabelFrame(root, text="Tests")
self.Tests.pack(anchor='w', pady=20)
for test in tests:
testcheck = ttk.Checkbutton(self.Tests, text=test)
testcheck.pack(side='left', anchor="n")
testbuttons.append(testcheck)
def select_tests():
for test in testbuttons:
test.invoke()
selecttests = ttk.Checkbutton(root, text="Select All",command=select_tests)
selecttests.place(x=260,y=16)
# --- middle ---
self.Managment = ttk.LabelFrame(root, text="Managment")
self.Managment.configure(width=10, height=20)
self.Managment.pack(anchor='nw', side='left')
for manage in managment:
managecheck = ttk.Checkbutton(self.Managment, text=manage)
managecheck.pack(anchor="w")
managebuttons.append(managecheck)
def select_manage():
for manage in managebuttons:
manage.invoke()
selectmanage = ttk.Checkbutton(self.Managment, text="Select All",command=select_manage)
selectmanage.pack()
self.FGCs = ttk.LabelFrame(root, text="FGCs")
self.FGCs.configure(width=10, height=20)
self.FGCs.pack(fill='y', expand=True, side='left', anchor='w')
self.sf = ScrolledFrame(self.FGCs)
self.sf.pack(fill='y', expand=True)
for fgc in FGCs:
fgccheck = ttk.Checkbutton(self.sf.inner, text=fgc)
fgccheck.pack(anchor="w")
fgcbuttons.append(fgccheck)
def select_fgc():
for fgc in fgcbuttons:
fgc.invoke()
selectfgc = ttk.Checkbutton(self.sf.inner, text="Select All", command=select_fgc)
selectfgc.pack()
root = Tk()
Window = mainwindow(root)
root.mainloop()

How to replace an existing image instead of adding additional images?

This is my first time here, and I would really appreciate some help with this.
So I have some code which runs a Tkinter tab and shows 2 buttons. If you click the first one, a picture of a cat appears.
However, if you click the button again, the same picture appears again at the bottom, making there 2.
If I click the other button, titled N/A, a different picture appears. But if you click the button again, the picture duplicates.
I want to make it so that when each button is pressed, the image is replaced, not duplicated.
Here is what I have so far.
from tkinter import *
root = Tk()
class HomeClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome to the game!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.FirstButton = Button(root, text="Start", bg="RED", fg="White",
command=self.FirstClick)
self.FirstButton.pack(side=LEFT, fill=X)
self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White",
command=self.SecondClick)
self.SecondButton.pack(side=LEFT, fill=X)
def FirstClick(self):
FirstPhoto = PhotoImage(file="keyboardcat.gif")
FiLabel = Label(root, image=FirstPhoto)
FiLabel.img = FirstPhoto
FiLabel.pack()
def SecondClick(self):
FirstPhoto = PhotoImage(file="donald.gif")
FiLabel = Label(root, image=FirstPhoto)
FiLabel.img = FirstPhoto
FiLabel.pack()
k = HomeClass(root)
root.mainloop()
That's becouse every time you click a button, you're calling FirstClick method which in turn creates new instance of PhotoImage class. I think it would be better to store FirstPhoto and in every FirstClick method call check if it is already has value or not.
class HomeClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome to the game!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.FirstButton = Button(root, text="Start", bg="RED", fg="White",
command=self.FirstClick)
self.FirstButton.pack(side=LEFT, fill=X)
self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White",
command=self.SecondClick)
self.SecondButton.pack(side=LEFT, fill=X)
self.FirstPhoto = None
def FirstClick(self):
if self.FirstPhoto is None:
self.FirstPhoto = PhotoImage(file="ksiazka.png")
self.FiLabel = Label(root, image=self.FirstPhoto)
self.FiLabel.img = self.FirstPhoto
self.FiLabel.pack()
Try this to change SecondPhoto
def SecondClick(self):
if self.SecondPhoto is None:
self.SecondPhoto = PhotoImage(file="ksiazka.png")
self.SecondPhotoLabel = Label(root, image=self.FirstPhoto)
self.SecondPhotoLabel.img = self.SecondPhoto
self.SecondPhotoLabel.pack()
Else:
self.SecondPhotoLabel.config(image='newimage')
self.SecondPhotoLabel.update()
Note - you can declare the newImage before as you have to read it with PhotoImage and then just put the image name in the .config
In this example you have two methods FirstClick, SecondClick to display an image and two methods to clear an first and second image accordingly: clearFirstImage, clearSecondImage. You just have to add two buttons to trigger those clear methods :)
from tkinter import *
from tkFileDialog import askopenfilename
root = Tk()
class HomeClass(object):
def __init__(self, master):
self.master = master
self.frame = Frame(master)
self.WelcomeLabel = Label(root, text="Welcome to the game!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.FirstButton = Button(root, text="Start", bg="RED", fg="White",
command=self.FirstClick)
self.FirstButton.pack(side=LEFT, fill=X)
self.SecondButton = Button(root, text="N/A", bg="Blue", fg="White",
command=self.SecondClick)
self.SecondButton.pack(side=LEFT, fill=X)
self.ToggleButtonText = "Show image"
self.ToggleButton = Button(root, text=self.ToggleButtonText, bg="Grey", fg="White",
command=self.ToggleClick)
self.ToggleButton.pack(side=LEFT, fill=X)
self.FirstPhoto = None
self.FiLabel = None
self.SecondPhoto = None
self.SecondPhotoLabel = None
self.ToggleButtonPhoto = None
self.ToggleButtonPhotoLabel = None
self.frame.pack()
def FirstClick(self):
if self.FirstPhoto is None:
self.FirstPhoto = PhotoImage(file="ksiazka.png")
self.FiLabel = Label(root, image=self.FirstPhoto)
self.FiLabel.img = self.FirstPhoto
self.FiLabel.pack()
def ToggleClick(self):
if self.ToggleButtonPhoto is None:
self.ToggleButtonPhoto = PhotoImage(file="ksiazka.png")
self.ToggleButtonPhotoLabel = Label(self.frame, image=self.ToggleButtonPhoto)
self.ToggleButtonPhotoLabel.img = self.ToggleButtonPhoto
self.ToggleButtonPhotoLabel.pack()
# and set label
self.ToggleButton.config(text="Hide image")
else:
self.ToggleButton.config(text="Show image")
self.ToggleButtonPhotoLabel.destroy()
self.ToggleButtonPhotoLabel.img = None
self.ToggleButtonPhotoLabel = None
self.ToggleButtonPhoto = None
self.frame.pack()
def SecondClick(self):
filename = askopenfilename()
allowed_extensions = ['jpg', 'png']
if len(filename) > 0 and filename.split('.')[-1] in allowed_extensions:
self.SecondPhoto = PhotoImage(file=filename)
self.SecondPhotoLabel = Label(root, image=self.SecondPhoto)
self.SecondPhotoLabel.img = self.SecondPhoto
self.SecondPhotoLabel.pack()
def clearFirstImage(self):
self.FirstPhoto = None
self.FiLabel = None
def clearSecondImage(self):
self.SecondPhoto = None
self.SecondPhotoLabel = None
k = HomeClass(root)
root.mainloop()
If you want to replace an existing image, first create the label the image is displayed in, and simply reconfigure only its image option with each click. Below is an example that does that:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def download_images():
# In order to fetch the image online
try:
import urllib.request as url
except ImportError:
import urllib as url
url.urlretrieve("https://i.stack.imgur.com/57uJJ.gif", "13.gif")
url.urlretrieve("https://i.stack.imgur.com/8LThi.gif", "8.gif")
class ImageFrame(tk.Frame):
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master, *args, **kwargs)
self._create_widgets()
self._display_widgets()
def _create_widgets(self):
def __create_image_label():
def ___load_images():
self.label.images = list()
self.label.images.append(tk.PhotoImage(file="8.gif"))
self.label.images.append(tk.PhotoImage(file="13.gif"))
self.label = tk.Label(self)
___load_images()
def __create_buttons():
self.buttons = list()
for i in range(2):
self.buttons.append(tk.Button(self, text=i,
command=lambda i=i: self.replace_image(i)))
__create_image_label()
__create_buttons()
def replace_image(self, button_index):
"""
Replaces the image in label attribute based on the index of the
button pressed.
"""
self.label['image'] = self.label.images[button_index]
def _display_widgets(self):
self.label.pack()
for i in range(2):
self.buttons[i].pack(fill='x', expand=True)
if __name__ == '__main__':
#download_images() # comment out after initial run
root = tk.Tk()
frame = ImageFrame(root)
frame.pack()
tk.mainloop()

Python/Tkinter: How to reduce the size of the expanded frames to their first positions?

According to the below codes; when the application is first run, two buttons display on the screen. If the user click one of the buttons, the frame is expanded and new buttons can be seen. If the user click the new buttons, another frame is expanded and new buttons can be seen again.
For example if the user first clicks the "English" button, the "Expand" button can be seen. And if the user click the "Expand" button, "Data" button can be seen. After that if the user click the "Turkish" button, the "Expand" button changes to "Genişlet" but the "Data" button still keeps on displaying, finally if the user clicks the "Genişlet" button, the "Data" button changes to "Veri".
But the above operation is not what i want to do. I want to change the "Veri" or "Data" buttons by clicking the "English" or "Turkish" buttons.
So, in order to do that, which parts of the codes i should modify? Thank you in advance.
import tkinter as tk
class App(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid(row=0, column=0, sticky="nsew")
self.b1 = tk.Button(master=self, text="Turkish", width=20)
self.b1.grid(row=0, column=0)
self.b2 = tk.Button(master=self, text="English", width=20)
self.b2.grid(row=0, column=1)
self.f1 = tk.Frame(master=master)
self.f1.grid(row=1, column=0)
self.f2 = tk.Frame(master=master)
self.f2.grid(row=2, column=0)
self.f3 = tk.Frame(master=self.f1)
self.f4 = tk.Frame(master=self.f1)
self.b3 = tk.Button(master=self.f3, text="Genişlet")
self.b3.grid(row=0, column=0)
self.b4 = tk.Button(master=self.f4, text="Expand")
self.b4.grid(row=0, column=0)
self.f5 = tk.Frame(master=self.f2)
self.f6 = tk.Frame(master=self.f2)
self.b5 = tk.Button(master=self.f5, text="Veri")
self.b5.grid(row=0, column=0)
self.b6 = tk.Button(master=self.f6, text="Data")
self.b6.grid(row=0, column=0)
self.configure_buttons()
#staticmethod
def activate(frame, parent):
for child in parent:
child.grid_forget()
frame.grid(row=0, column=0)
def configure_buttons(self):
self.b1.configure(command=lambda: self.activate(self.f3, self.f1.winfo_children()))
self.b2.configure(command=lambda: self.activate(self.f4, self.f1.winfo_children()))
self.b3.configure(command=lambda: self.activate(self.f5, self.f2.winfo_children()))
self.b4.configure(command=lambda: self.activate(self.f6, self.f2.winfo_children()))
if __name__ == "__main__":
root = tk.Tk()
frame = App(master=root)
frame.mainloop()
Here is an example that keeps the functionality you currently have while being able to apply the language changes using textvariable and stringVar()
There is a better way I am sure but for this simple program this should suffice.
I created two variables set to a StringVar() The first 2 buttons are linked to a function/method that will change the strings for each stringVar to reflect the language choice.
I also created some place holder variables to use until the other buttons needed to be created. Let me know what you think of this option.
Update: I added a menu that will remove all the buttons except for the starting 2 buttons. Effectively a restart.
import tkinter as tk
class App(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.master = master
self.btn1_text = tk.StringVar()
self.btn1_text.set("Expand")
self.btn2_text = tk.StringVar()
self.btn2_text.set("Data")
self.second_frame = "None"
self.btn2 = "None"
self.master.columnconfigure(0, weight = 1)
self.top_frame = tk.Frame(self.master)
self.top_frame.grid(row = 0, column = 0, sticky = "ew")
self.turkish_button = tk.Button(self.top_frame, text="Turkish", width=20, command = lambda: self.change_lang_and_add_btn1("turkish"))
self.turkish_button.grid(row=0, column=0)
self.english_button = tk.Button(self.top_frame, text="English", width=20, command = lambda: self.change_lang_and_add_btn1("english"))
self.english_button.grid(row=0, column=1)
self.menu = tk.Menu(self.master)
self.master.config(menu = self.menu)
self.file_menu = tk.Menu(self.menu, tearoff = 0)
self.menu.add_cascade(label = "File", menu = self.file_menu)
self.file_menu.add_command(label = "Reset", command = self.reset_buttons)
def change_lang_and_add_btn1(self, choice):
if choice == "english":
self.btn1_text.set("Expand")
self.btn2_text.set("Data")
if choice == "turkish":
self.btn1_text.set("Genişlet")
self.btn2_text.set("Veri")
if self.second_frame == "None":
self.second_frame = tk.Frame(self.master)
self.second_frame.grid(row = 1, column = 0, columnspan = 2)
self.btn1 = tk.Button(self.second_frame, textvariable = self.btn1_text, width=20, command = lambda: self.add_btn2())
self.btn1.grid(row = 1, column = 0, columnspan = 2)
def add_btn2(self):
if self.btn2 == "None":
self.btn2 = tk.Button(self.second_frame, textvariable = self.btn2_text, width=20)
self.btn2.grid(row = 2, column = 0, columnspan = 2)
def reset_buttons(self):
if self.second_frame != "None":
self.second_frame.destroy()
self.second_frame = "None"
self.btn2 = "None"
if __name__ == "__main__":
root = tk.Tk()
frame = App(root)
frame.mainloop()

Categories