I want to hide/remove all the buttons from my window (temporarily) with the "hide_widgets" function so I can put them back after but its just not working for me, I have tried using grid_hide() and destroy() and anything I have tried so for from searching stackoverflow as not worked either.
Here is my program so far:
from tkinter import *
class Application(Frame):
#GUI Application
def __init__(self, master):
#Initialize the Frame
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
#Create new game etc...
#Title
self.title = Label(self,text = "Gnome")
self.title.grid()
#New Game
self.new_game = Button(self,text = "New Game")
self.new_game ["command"] = self.create_new_game
self.new_game.grid()
#Load Game
self.load_game = Button(self,text = "Load Game")
self.load_game ["command"] = self.display_saves
self.load_game.grid()
#Settings
self.settings = Button(self,text = "Settings")
self.settings ["command"] = self.display_settings
self.settings.grid()
#Story
self.story = Button(self,text = "Story")
self.story ["command"] = self.display_story
self.story.grid()
#Credits
self.credits = Button(self,text = "Credits")
self.credits ["command"] = self.display_credits
self.credits.grid()
def hide_widgets(self):
#clear window
new_game.grid_forget()
def create_new_game(self):
#Create new game file
self.hide_widgets
self.instruction = Label(self, text = "Name World:")
self.instruction.grid()
self.world_name = Entry(self)
self.world_name.grid()
def display_saves(self):
#display saved games and allow to run
print("saves")
def display_settings(self):
#display settings and allow to alter
print("settings")
def display_story(self):
#display story
print("story")
def display_credits(self):
#display credits
print("credits")
root = Tk()
root.title("Welcome")
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry('%dx%d+0+0' % (width,height))
app = Application(root)
root.mainloop()
Thank you in advance.
You can hide the Buttons by calling each one's grid_forget() method.
To make that easier you might want to create a self.buttons list or dictionary that contains them all.
Alternatively there's also a grid_slaves() method you might be able to use on the Application instance that will give you a list of all the widgest it manages (or just the ones in a specified row or column). The Buttons should be in one of these lists. I've never used it, so I don't know how easy it would be to identify them in the list returned however.
Ok I got it working now, silly me forgot "()" in self.hide_widgets(), i just never thought about it because there was no error as it was creating a variable instead.
Have you tried replacing new_game.grid_forget() with self.new_game.grid_forget()?
Check this answer out for an explanation as to why self needs to be referenced explicitly. I ran a very simple script to test this behavior and it worked fine.
Related
Hello I think I have a python tkinter design issue. I have looked on this to structure my code better. I do not want to change the configuration of all my widgets individually and would like to use parent_widget.winfo_children() command that I found from this question.
I am wondering is there a better way to not individually configure the widgets and yet update their font and Style.
Here is my code and the current behavior:
class TabOne(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.tab1_note = ttk.Notebook(self,width=parent.winfo_screenwidth(), height=parent.winfo_screenheight())
tab1_open_observations = ttk.Frame(self.tab1_note)
tab1_closed_observations = ttk.Frame(self.tab1_note)
self.tab1_note.add(tab1_open_observations, text= "Open Projects")
self.tab1_note.add(tab1_closed_observations, text= "Closed/Deferred Projects")
self.tab1_note.pack()
self.tab_two_load(tab1_open_observations)
self.tab_three_load(tab1_closed_observations)
widget_list = []
widget_list.extend(tab1_open_observations.winfo_children())
widget_list.extend(tab1_closed_observations.winfo_children())
for wid in widget_list:
try:
wid.configure(font = 'helvetica 12')
except:
pass
def tab_one_load(self,tab1_refresh_db):
def tab_two_load(self,tab1_open_observations)
class TabTwo(Frame):
class TabThree(Frame):
class MainWindow(Frame):
def __init__(self, window, **kwargs):
Frame.__init__(self, window, **kwargs)
self.load_ui()
def load_ui(self):
self.note = ttk.Notebook(self,width=self.window.winfo_screenwidth()-(2*self.pad), height=self.window.winfo_screenheight()-(2*self.pad))
self.tab1 = TabOne(self.note)
self.tab2 = TabTwo(self.note)
self.tab3 = TabThree(self.note)
self.note.pack()
def main():
window = Tk()
window.title('Productivity Tool')
app = MainWindow(window)
app.pack(side="top", fill="both", expand=True)
window.mainloop()
if __name__ == '__main__':
main()
Current behavior for dependent drop down lists (code below):
The second list does not overlap if I add project_module_dropdown.configure(font='helvetica 12') below every dependent OptionsMenu, Here is more code for the function tab_two_load()
def tab_two_load(self,tab1_open_observations):
def update_modules(a,b,c):
proj_mo_names = [module[0] for module in project_modules]
proj_mod_select.set(proj_mo_names[0])
project_module_dropdown = OptionMenu(tab1_open_observations,proj_mod_select,*proj_mo_names)
project_module_dropdown.configure(font='helvetica 12')
project_module_dropdown.grid(row=2, column=1,padx=10, pady=10)
proj_select = StringVar(tab1_open_observations,value='Default Text')
proj_select.trace('w',update_modules)
proj_mod_select = StringVar(tab1_open_observations,value='Default Text')
proj_mod_select.trace('w',update_teams)
proj_mod_select.trace('w',update_artifacts)
proj_names = [project[1] for project in projects]
proj_select.set(proj_names[0])
project_dropdown = OptionMenu(tab1_open_observations,proj_select,*proj_names)
project_dropdown.grid(row=1,column=1,padx=10,pady=10)
I think the problem is with how I have structured my code but i believe i have compartmentalized the code well but I am open to suggestions. this is not exactly a code review problem. My problem is overlapping drowdowns, but I feel that I have some duplication in my code that I would like to avoid. Any help is great. Thanks.
I would like this as my desired behavior without adding project_module_dropdown.configure(font='helvetica 12'):
I have made a small application with tkinter and Python 3 which has four buttons on the top of the window to form a menu. It works fine but I want to know how to make the buttons appear along the window over a period of time starting from a single button in the center when first started rather than being statically placed in the center.
Here is my script so far:
import tkinter as tk
class utilities(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.window()
def window(self):
self.pluginrun = tk.Button(self)
self.pluginrun["text"] = "Run Existing Plugin"
self.pluginrun["command"] = self.run_plugin
self.pluginrun.pack(side="left")
self.owning = tk.Button(self)
self.owning["text"] = "Add A New Plugin"
self.owning["command"] = self.plugin
self.owning.pack(side="left")
self.webpage = tk.Button(self)
self.webpage["text"] = "Webpage"
self.webpage["command"] = self.web
self.webpage.pack(side="left")
self.more_info = tk.Button(self)
self.more_info["text"] = "More"
self.more_info["command"] = self.more
self.more_info.pack(side="left")
def run_plugin(self):
print('Running Plugin')
def plugin(self):
print('Available Extensions')
def web(self):
print("Opening Webpage To Python.org")
def more(self):
print('Made Entirely In Python')
root = tk.Tk()
root.geometry('500x500')
show = utilities(master=root)
show.mainloop()
Which gives this result:
When first opened I would like it to look like this:
and over a period of time for more buttons to appear alongside one at a time until it looks like the first image.
How can this be done?
You can add all your buttons to a list and then use a repeating timed method to pack each button in the list one at a time at a set interval.
I created a counter that we can use to keep track of what button is going to be packed next from the list.
I also created a new list to store all the buttons in.
Then I modified your window() method to add each button to the list instead.
The last thing was to create a timed method that would use the self.counter attribute I created to keep track of what button is to be packed next.
In tkinter the best method to use to keep a timed loop or set a timer for anything is to use after(). Using sleep() or wait() in tkinter will only cause the entire tkinter app to freeze.
Take a look at the below code.
import tkinter as tk
class utilities(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.list_of_buttons = []
self.counter = 0
self.window()
def window(self):
for count in range(4):
self.list_of_buttons.append(tk.Button(self))
pluginrun = self.list_of_buttons[0]
pluginrun["text"] = "Run Existing Plugin"
pluginrun["command"] = self.run_plugin
owning = self.list_of_buttons[1]
owning["text"] = "Add A New Plugin"
owning["command"] = self.plugin
webpage = self.list_of_buttons[2]
webpage["text"] = "Webpage"
webpage["command"] = self.web
more_info = self.list_of_buttons[3]
more_info["text"] = "More"
more_info["command"] = self.more
self.timed_buttons()
def timed_buttons(self):
if self.counter != len(self.list_of_buttons):
self.list_of_buttons[self.counter].pack(side ="left")
self.counter +=1
root.after(1500, self.timed_buttons)
def run_plugin(self):
print('Running Plugin')
def plugin(self):
print('Available Extensions')
def web(self):
print("Opening Webpage To Python.org")
def more(self):
print('Made Entirely In Python')
root = tk.Tk()
root.geometry('500x500')
show = utilities(master=root)
show.mainloop()
Add the Buttons inside a Frame, which you centre, and then as you add more Buttons, the Frame should centre them. If not, you may need to call root.update(), to re-centre the Frame.
I have an issue where my image label will not update. I have used a large combination of root.update() root.update_idletasks() etc, I have also gone through many posts around the internet attempting to use their solutions but to no avail.
I have the code split to one class and two functions, the first function will check if the user has the right spelling or not, the second will pick a new random word and image from a dict.
The issue is that the image will not update, the print command is working so the class and funcs are working fine.
here is the code thus far, I am new to using Class and init I thought the best way to test out the .update of tkinter is a spelling game
from tkinter import *
import random
words = {"apple": "apple.gif", "car": "car.gif"}
MAIN_FONT = "Helvetica", 16
root = Tk()
class mainFrame:
def __init__(self):
self.pick_random = "..."
#MAIN TITLE OF THE APP
main_title = Label(root, text="Spelling", font=MAIN_FONT)
main_title.pack()
#END OF MAIN TITLE
#START OF IMAGE
self.img = PhotoImage(file=self.pick_another() + ".png")
self.show_image = Label(root, image=self.img)
self.show_image.configure(image=self.img)
self.show_image.image = self.img
self.show_image.pack()
#END OF IMAGE
#START OF ENTRY AND BUTTON INPUTS
self.main_entry = Entry(root)
self.submit_btn = Button(root, text="Submit", command=self.submit)
self.main_entry.pack()
self.submit_btn.pack()
#END OF ENTRY AND BUTTON INPUTS
def submit(self):
if self.main_entry.get() == self.pick_random:
print("RIGHT")
self.pick_another()
else:
print("That's not right, try again")
def pick_another(self):
print("Called")
self.pick_random = random.choice(list(words.keys()))
print(self.pick_random)
root.update_idletasks()
return self.pick_random
app = mainFrame()
root.mainloop()
As I said this does kind of work, The first image will show up and inputting the correct spelling for the image will generate a new word but the image does not update.
I have spent a few days working on various scripts trying to get tkinter to update, but it will not.
I would be very grateful for any help in this
I am having a problem with a fairly simple app.
It performs properly, but I would like it to perform a little slower.
The idea is to randomly generate a name from a list, display it, then remove it fromthe list every time a button is clicked.
To make it a little more interesting, I want the program to display several names before
picking the last one. I use a simple for loop for this. However, the code executes so quickly, the only name that winds up displaying is the last one.
using time.sleep() merely delays the display of the last name. no other names are shown.
here is my code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *
import random
import time
class Application(Frame):
def __init__(self, master):
""" Initialize the frame. """
super(Application, self).__init__(master)
self.grid()
self.name_list = ["Thorin","Tyler","Jose","Bryson","Joe"]
self.create_widget()
def create_widget(self):
self.lbl = Label(self)
self.lbl["text"] = "Click to spin"
self.lbl["font"] = ("Arial", 24)
self.lbl.grid()
self.bttn = Button(self)
self.bttn["text"]= "Spin"
self.bttn["command"] = self.spin
self.bttn.grid()
def spin(self):
if self.name_list:
for i in range(5):
index = random.randrange(len(self.name_list))
self.lbl["text"] = self.name_list[index]
self.lbl.grid()
self.name_list.pop(index)
else:
self.lbl["text"] = "No more names"
self.lbl.grid()
def main():
root = Tk()
root.title("Click Counter")
root.geometry("600x600")
app = Application(root)
root.mainloop()
if __name__ == '__main__':
main()
This is a pretty common class of problems related to GUI programming. The heart of the issue is the window drawing manager. As long as your function is executing, the drawing manager is frozen; updating the label's text will have no apparent effect until your function ends. So if you have a for loop with a sleep(1) command inside, all it will do is freeze everything for five seconds before updating with your final value when the function finally ends.
The solution is to use the after method, which tells Tkinter to call the specified function at some point in the future. Unlike sleep, this gives the drawing manager the breathing room it requires to update your window.
One possible way to do this is to register six events with after: five for the intermediate name label updates, and one for the final name change and pop.
def spin(self):
def change_name():
index = random.randrange(len(self.name_list))
self.lbl["text"] = self.name_list[index]
self.lbl.grid()
def finish_spinning():
index = random.randrange(len(self.name_list))
self.lbl["text"] = self.name_list[index]
self.lbl.grid()
self.name_list.pop(index)
if self.name_list:
name_changes = 5
for i in range(name_changes):
self.after(100*i, change_name)
self.after(100*name_changes, finish_spinning)
else:
self.lbl["text"] = "No more names"
self.lbl.grid()
(disclaimer: this is only a simple example of how you might use after, and may not be suitable for actual use. In particular, it may behave badly if you press the "spin" button repeatedly while the names are already spinning. Also, the code duplication between change_name and finish_spinning is rather ugly)
The code as it is can show the same item twice since it chooses a new random number each time and so will choose the same number part of the time. Note that you do not pop until after the loop which means that each time you run the program you will have one less name which may or may not be what you want. You can use a copy of the list if you want to keep it the same size, and/or random.shuffle on the list and display the shuffled list in order. Also you only have to grid() the label once,
class Application():
def __init__(self, master):
""" Initialize the frame. """
self.master=master
self.fr=Frame(master)
self.fr.grid()
self.name_list = ["Thorin","Tyler","Jose","Bryson","Joe"]
self.ctr=0
self.create_widget()
def create_widget(self):
self.lbl = Label(self.master width=30)
self.lbl["text"] = "Click to spin"
self.lbl["font"] = ("Arial", 24)
self.lbl.grid()
self.bttn = Button(self.master)
self.bttn["text"]= "Spin"
self.bttn["command"] = self.spin
self.bttn.grid()
def change_label(self):
self.lbl["text"] = self.name_list[self.ctr]
self.ctr += 1
if self.ctr < 5:
self.master.after(1000, self.change_label)
else:
self.ctr=0
def spin(self):
if self.name_list and 0==self.ctr: # not already running
random.shuffle(self.name_list)
self.change_label()
else:
self.lbl["text"] = "No more names"
if __name__ == '__main__':
root = Tk()
root.title("Click Counter")
root.geometry("600x600")
app = Application(root)
root.mainloop()
i am going to create an tkinter gui app, and i know how i want it to look. but after playing around with tkinter, i found no way to toggle between screens when you press buttons down at the bottom. i know it does nothing but below is the simple layout i want to have, and switch between "myframe1" and "myframe2" kind of like the Apple App Store layout. is this possible?
from tkinter import *
tk = Tk()
tk.geometry("300x300")
myframe1 = Frame(tk,background="green",width=300,height=275)
myframe1.pack()
myframe2 = Frame(tk,background="cyan",width=300,height=275)
myframe2.pack()
btnframe = Frame(tk)
btn1 = Button(btnframe,text="screen1",width=9)
btn1.pack(side=LEFT)
btn2 = Button(btnframe,text="screen2",width=9)
btn2.pack(side=LEFT)
btn3 = Button(btnframe,text="screen3",width=9)
btn3.pack(side=LEFT)
btn4 = Button(btnframe,text="screen4",width=9)
btn4.pack(side=LEFT)
myframe1.pack()
btnframe.pack()
tk.mainloop()
something for you to get started with:
def toggle(fshow,fhide):
fhide.pack_forget()
fshow.pack()
btn1 = Button(btnframe,text="screen1", command=lambda:toggle(myframe1,myframe2),width=9)
btn1.pack(side=LEFT)
btn2 = Button(btnframe,text="screen2",command=lambda:toggle(myframe2,myframe1),width=9)
btn2.pack(side=LEFT)
Are you looking for something like a tabbed widget? You could use forget and pack as suggested here
Here is a class that I use in my code that works:
class MultiPanel():
"""We want to setup a pseudo tabbed widget with three treeviews. One showing the disk, one the pile and
the third the search results. All three treeviews should be hooked up to exactly the same event handlers
but only one of them should be visible at any time.
Based off http://code.activestate.com/recipes/188537/
"""
def __init__(self, parent):
#This is the frame that we display
self.fr = tki.Frame(parent, bg='black')
self.fr.pack(side='top', expand=True, fill='both')
self.widget_list = []
self.active_widget = None #Is an integer
def __call__(self):
"""This returns a reference to the frame, which can be used as a parent for the widgets you push in."""
return self.fr
def add_widget(self, wd):
if wd not in self.widget_list:
self.widget_list.append(wd)
if self.active_widget is None:
self.set_active_widget(0)
return len(self.widget_list) - 1 #Return the index of this widget
def set_active_widget(self, wdn):
if wdn >= len(self.widget_list) or wdn < 0:
logger.error('Widget index out of range')
return
if self.widget_list[wdn] == self.active_widget: return
if self.active_widget is not None: self.active_widget.forget()
self.widget_list[wdn].pack(fill='both', expand=True)
self.active_widget = self.widget_list[wdn]