When a resize event is triggered, how could I retrieve the toplevel, from which this event was triggered?
I have written a small programm, where the main window has a button that opens another window and each new window gets a binding for the resize method that currently prints the height and width of the window. In the main project, the toplevel is used as an index for lists to retrieve information for that specific window, so it would be ideal to be able to retrieve the toplevel as well. Is that possible, either directly or indirectly?
import tkinter as tk
class MyApp(tk.Frame):
def __init__(self, master = None):
self.main()
tk.Frame.__init__(self, master)
def main(self):
btn = tk.Button(root, text="New Window", command=self.neues_fenster)
btn.grid(row=0, column = 0)
def neues_fenster(self):
top = tk.Toplevel()
top.title("Some Window")
top.minsize(width = 150, height = 150)
top.bind("<Configure>", self.resize)
def resize(self, event):
print("width", event.width, "height", event.height)
if __name__=="__main__":
root = tk.Tk()
myapp = MyApp(master = root)
myapp.mainloop()
In effbot document,You could use event.widget to get the widget.(It is also okay even if it is toplevel).
All the possible attributes of event:
Related
I made a button that plus the x axis with 50 if i press it.If i press the button tho it doesn't move,yes it changes the value but doesn't move. I tried a while loop but it crashed the program.
In general we use pack and grid geometry managers to handle widget placement in Tk. However, if you want to explicitly control the placement then you can use place which allows you to specify the location in either pixel or relative coordinates.
Here is an example of a frame with a button inside that moves when you click the button. Note that the button is positioned relative to its parent container so moves with the frame.
import tkinter as tk
import tkinter.ttk as ttk
class App(ttk.Frame):
def __init__(self, master, **kwargs):
super(App, self).__init__(master=master, **kwargs)
master.wm_geometry('640x480')
self.frame = f = tk.Frame(self, width=200, height=80, relief=tk.SUNKEN, borderwidth=2)
b = ttk.Button(f, text="Move", command=self.move_frame)
b.place(x=2, y=2)
f.place(x=2, y=2)
self.place(relheight=1.0, relwidth=1.0)
def move_frame(self):
x = self.frame.winfo_x()
x = x + 10
self.frame.place(x=x)
def main():
root = tk.Tk()
app = App(root)
root.mainloop()
if __name__ == '__main__':
main()
I have created few windows using Tkinter. I need help in the implementation of switching from one window to another when the button has been clicked.
All windows that are created should have the same size.
And also I want to clear existing window data and show next window data.
If you want to have multiple windows opened and want to switch between each window with all of their widgets intact then I don't think destroying a window each time you switch is a good idea instead you can try to withdraw and deiconify the windows.
I've created something like this which can switch between windows and maintain the same geometry of the previous window as you said.
import tkinter as tk
class Window(tk.Toplevel):
# List to keep the reference of all the toplevel windows
_info_pages = []
def __init__(self, master=None, cnf={}, **kw):
kw = tk._cnfmerge( (cnf,kw) )
width = kw.pop('width', master.winfo_width()) # 250x250 will be the standard size of the window
height = kw.pop('height', master.winfo_height())
title = kw.pop('title', 'Win %s' %(len(self._info_pages)+1) )
super(Window, self).__init__(master=master, cnf=cnf, **kw)
for i in self._info_pages: i.wm_withdraw() # Hide the previous windows
if self._info_pages and width == master.winfo_width():
self.wm_geometry(self._info_pages[-1].winfo_geometry())
else:
self.wm_geometry("%dx%d+%d+%d" % (width, height,
master.winfo_rootx()+master.winfo_width(), master.winfo_rooty()))
self._info_pages.append(self)
self.title(title)
self.B1 = tk.Button(self, text='◀ Prev', padx=5, command=self.switch_to_prev)
self.B1.place(relx=0, rely=1, anchor='sw')
self.B2 = tk.Button(self, text='Next ▶', padx=5, command=self.switch_to_next)
self.B2.place(relx=1, rely=1, anchor='se')
self.enable_disable_button()
def enable_disable_button(self):
"""Enable and disable the buttons accordingly if there is no window."""
for i in self._info_pages:
if i == self._info_pages[0]: i.B1['state'] = 'disabled'
else: i.B1['state'] = 'normal'
if i == self._info_pages[-1]: i.B2['state'] = 'disabled'
else: i.B2['state'] = 'normal'
def switch_to_prev(self):
"""Switch to the previous window"""
index = self._info_pages.index(self)
if index != 0:
for i in self._info_pages:
i.wm_withdraw()
self._info_pages[index-1].geometry(self.winfo_geometry())
self._info_pages[index-1].wm_deiconify()
def switch_to_next(self):
"""Switch to the next window"""
index = self._info_pages.index(self)
if index+1 != len(self._info_pages):
for i in self._info_pages:
i.wm_withdraw()
self._info_pages[index+1].geometry(self.winfo_geometry())
self._info_pages[index+1].wm_deiconify()
def destroy(self):
"""if a window is destroyed this will open the last window in the list"""
self._info_pages.remove(self)
if self._info_pages:
self._info_pages[-1].geometry(self.winfo_geometry())
self._info_pages[-1].wm_deiconify()
self.enable_disable_button()
return super().destroy()
# This is just a demo
if __name__ == '__main__':
import random as rnd
root = tk.Tk()
root.geometry('250x250')
root.title("I'm the main window")
colorlist = ['beige','bisque','black','blanchedalmond','blue','blueviolet',
'burlywood', 'cadetblue','chartreuse','chocolate' ]
def create_window():
Window(root, bg=rnd.choice(colorlist))
tk.Button(root, text='Create Window', command=create_window).pack()
root.mainloop()
I used TKinter in python2.
My code is as follow.
from Tkinter import *
class Application(Frame):
def __init__(self, master=None,w=1000,h=600):
Frame.__init__(self, master)
self.createWidgets(master,w,h)
def getRadio(self,widget):
widget.deselect()
def createWidgets(self, master,w,h):
ConfigPane=Frame(master,bg='lightblue',width=int((w/6)*4),height=int(h/3),padx=5,pady=5)
DisplayPane=Frame(master,bg='DarkOliveGreen1',width=int((w/6)*4),height=int((h/3)*2),padx=5,pady=5)
HyperPane=Frame(master,bg='khaki1',width=int((w/6)*2),height=h,padx=5,pady=5)
# layout all of the main containers
root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)
ConfigPane.grid(row=0,column=0,columnspan=4,rowspan=1, sticky=W+N)
DisplayPane.grid(row=1,columnspan=4,rowspan=2, sticky=W+S)
HyperPane.grid(row=0,column=5,columnspan=2,rowspan=3, sticky=E+N+S)
# create the widgets for the top frame
var=StringVar()
RegNet = Radiobutton(ConfigPane, text='RegNet',variable=var,pady=10,padx=10,width=10,anchor='w',command=lambda:self.getRadio(RegNet))
RegNet.grid(row=0,column=0)
InceptionNet = Radiobutton(ConfigPane, text='InceptionNet',variable=var,pady=1,padx=10,width=10,anchor='w',command=lambda:self.getRadio(InceptionNet))
InceptionNet .grid(row=1,column=0)
ResNet = Radiobutton(ConfigPane, text='ResNet',variable=var,pady=8,padx=10,width=10,anchor='w',command=lambda:self.getRadio(ResNet))
ResNet.grid(row=2,column=0)
if __name__ == "__main__":
root = Tk()
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
root.geometry(str(width)+'x'+str(height))
app = Application(master=root,w=width,h=height)
app.master.title('Deep Learning Reconfigurable Platform')
app.mainloop()
root.destroy()
When I click the radiobutton, the black dot at the button is supposed to disappear, but it doesn't. How can I make it work?
Every radiobutton needs a distinct value, otherwise they all have the same value and thus show the same state. The value is how tkinter knows which button in a set of buttons should be selected.
You probably shouldn't be calling deselect in the callback -- that makes your buttons effectively useless, since any attempt by the user to choose one will cause whatever they clicked on to immediately be deselected. It will become impossible for them to select anything.
The key elements:
The "var", must be defined in scope of Class, if not it is destroyed when exiting the createWidget method and you would need to navigate through the widgets to get the selected one.
The RadioButtons are missing the value attribute, defining what is the value to be set to the "var" when selected.
Here is the updated code; updated for Python3 (changed the module tkinter name)
from tkinter import *
class Application(Frame):
var = None
def __init__(self, master=None,w=1000,h=600):
Frame.__init__(self, master)
self.var = IntVar()
self.var.set(1)
self.createWidgets(master, w, h)
def show_choice(self):
#for widget in widgets:
# widget.deselect()
print(self.var.get())
return
def createWidgets(self, master,w,h):
ConfigPane=Frame(master,bg='lightblue',width=int((w/6)*4),height=int(h/3),padx=5,pady=5)
DisplayPane=Frame(master,bg='DarkOliveGreen1',width=int((w/6)*4),height=int((h/3)*2),padx=5,pady=5)
HyperPane=Frame(master,bg='khaki1',width=int((w/6)*2),height=h,padx=5,pady=5)
# layout all of the main containers
root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)
ConfigPane.grid(row=0,column=0,columnspan=4,rowspan=1, sticky=W+N)
DisplayPane.grid(row=1,columnspan=4,rowspan=2, sticky=W+S)
HyperPane.grid(row=0,column=5,columnspan=2,rowspan=3, sticky=E+N+S)
# create the widgets for the top frame
RegNet = Radiobutton(ConfigPane, text='RegNet',variable=self.var,pady=10,padx=10,width=10,anchor='w', value=1, command=self.show_choice)
RegNet.grid(row=0,column=0)
InceptionNet = Radiobutton(ConfigPane, text='InceptionNet',variable=self.var,pady=1,padx=10,width=10,anchor='w', value=2, command=self.show_choice)
InceptionNet.grid(row=1,column=0)
ResNet = Radiobutton(ConfigPane, text='ResNet',variable=self.var,pady=8,padx=10,width=10,anchor='w', value=3, command=self.show_choice)
ResNet.grid(row=2,column=0)
if __name__ == "__main__":
root = Tk()
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
root.geometry(str(width)+'x'+str(height))
app = Application(master=root,w=width,h=height)
app.master.title('Deep Learning Reconfigurable Platform')
app.mainloop()
# root.destroy()
In the following code, when I press the button to add some secondary windows, and then try to close a window by using "Command-w" it does not always close the active window. But if I disable the menu creation by commenting the line self.gerar_menu(), windows are opened and closed as expected (I mean, by clicking the red 'x' button or by pressing Command-W in OS X). Any idea about what is wrong here?
Here is my current test code:
#!/usr/bin/env python3.6
# encoding: utf-8
import tkinter as tk
import tkinter.font
from tkinter import ttk
class baseApp(ttk.Frame):
"""
Parent classe for main app window (will include some aditional methods and properties).
"""
def __init__(self, master, *args, **kwargs):
super().__init__(master, *args, **kwargs)
self.master = master
self.mainframe = ttk.Frame(master)
self.mainframe.pack()
class App(baseApp):
""" Base class for the main application window """
def __init__(self, master, *args, **kwargs):
super().__init__(master, *args, **kwargs)
self.master = master
#self.gerar_menu() # This line breaks "Command-w" functionality
self.lbl_text = ttk.Label(self.mainframe, text="This is the Main Window")
self.lbl_text.pack()
self.btn = ttk.Button(self.mainframe, text="Open Second window",
command=lambda: self.create_detail_window(self, number=0))
self.btn.pack()
self.newDetailsWindow = {}
self.windows_count=0
def gerar_menu(self):
""" generate the application menu """
self.menu = tk.Menu(root)
root.config(menu=self.menu)
self.fileMenu = tk.Menu(self.menu)
self.menu.add_cascade(label="File", menu=self.fileMenu)
self.fileMenu.add_command(label="New Document", command=None, accelerator="Command+n")
def create_detail_window(self, *event, number=None):
self.windows_count += 1
self.newDetailsWindow[self.windows_count]=tk.Toplevel()
self.newDetailsWindow[self.windows_count].geometry('900x600+80+130')
self.newDetailsWindow[self.windows_count].title(f'Detail: {self.windows_count}')
self.newDetailsWindow[self.windows_count].wm_protocol("WM_DELETE_WINDOW", self.newDetailsWindow[self.windows_count].destroy)
self.newDetailsWindow[self.windows_count].bind("Command-w", lambda event: self.newDetailsWindow[-1].destroy())
self.detail_window = detailWindow(self.newDetailsWindow[self.windows_count], self.windows_count)
self.newDetailsWindow[self.windows_count].focus()
print(self.newDetailsWindow)
class detailWindow(ttk.Frame):
""" Base class for secondary windows """
def __init__(self, master, rep_num, *args,**kwargs):
super().__init__(master,*args,**kwargs)
self.num_rep = rep_num
self.master.minsize(900, 600)
self.master.maxsize(900, 600)
print(f"Showing details about nr. {self.num_rep}")
self.mainframe = ttk.Frame(master)
self.mainframe.pack()
self.lbl_text = ttk.Label(self.mainframe,
text=f"Showing details about nr. {self.num_rep}")
self.lbl_text.pack()
if __name__ == "__main__":
root = tk.Tk()
janela_principal = App(root)
root.title('Main Window')
root.bind_all("<Mod2-q>", exit)
root.mainloop()
If you want to create a binding for closing a window, you need the function to act upon the actual window that received the event. Your code is always deleting the last window that was opened no matter which window received the event.
The first step is to bind to a function rather than using lambda. While lambda has its uses, binding to a named function is much easier to debug and maintain.
Once the function is called, the event object can tell you which window got the event via the widget attribute of the event object. Given this window, you can get the toplevel window that this window is in (or itself, if it's a toplevel window) via the winfo_toplevel command.
For example:
window = tk.Toplevel(...)
...
window.bind("<Command-w>", self.destroy_window)
...
def destroy_window(self, event):
window = event.widget.winfo_toplevel()
window.destroy()
I am trying to make a large text-entry popup as part of a gui. The idea is to get paragraph-long user-input. The problem is that the method get_big_text() returns before the button is pushed. How can I have a separate window pop-up like this, and be able to save the user's text to a variable in my control program? Everything else in my program has been working out, until I tried to implement this. I am new to gui programming. I get the feeling that there is something fundamentally different about waiting for user input here, but I can't wrap my head around it in the functional context.
My goal is to have the line print(foo.get_big_text()) print the user's text, but of course it prints None because the get_big_text() method finishes.
I have left out the details of the rest of the gui, and wrote an __init__() that probably doesn't need to be there, but this is the basics of how my gui is coming along. The Toplevel widget is the only widget in my gui that is not somehow connected to root.
from tkinter import *
class Gui:
def __init__(self, root):
tframe = Frame(root)
tframe.pack(side='top')
bframe = Frame(root)
bframe.pack(side='bottom')
self.txt = Text(tframe)
self.txt.insert('0.0', 'Totally foobar')
self.txt.pack()
self.btn = Button(bframe, text='OK')
self.btn.pack()
def get_big_text(self, title='', text=''):
popup = Toplevel(height=160, width=180)
popup.title(title)
txtframe = Frame(popup)
txtframe.pack()
big_text = Text(txtframe)
big_text.insert('0.0',text)
big_text.pack()
btnframe = Frame(popup)
btnframe.pack()
grab_text = Button(btnframe)
grab_text.config(text="Done", command=lambda: big_text.get('0.0', 'end'))
grab_text.pack()
root=Tk()
root.title('Example')
foo = Gui(root)
print(foo.get_big_text())
root.mainloop()
You should pass the text to one function in your class and then do whatever you want with it (like printing):
from Tkinter import *
class Gui:
def __init__(self, root):
tframe = Frame(root)
tframe.pack(side='top')
bframe = Frame(root)
bframe.pack(side='bottom')
self.txt = Text(tframe)
self.txt.insert('0.0', 'Totally foobar')
self.txt.pack()
self.btn = Button(bframe, text='OK')
self.btn.pack()
def f(self, text):
print(text)
def get_big_text(self, title='', text=''):
popup = Toplevel(height=160, width=180)
popup.title(title)
txtframe = Frame(popup)
txtframe.pack()
big_text = Text(txtframe)
big_text.insert('0.0',text)
big_text.pack()
btnframe = Frame(popup)
btnframe.pack()
grab_text = Button(btnframe)
grab_text.config(text="Done", command=lambda: self.f(big_text.get('0.0', 'end')))
grab_text.pack()
root=Tk()
root.title('Example')
foo = Gui(root)
foo.get_big_text()
root.mainloop()
If you want to print the text after the gui finished you can do this modifications:
On Gui.f:
def f(self, text):
self.text = text
At the end of your code:
root.mainloop()
print(foo.text)
After some suggestions from #xndrme, and some hard thinking, I realized the solution is quite simple. It's just that I'm not used to programing in this functional style. Really fun to discover this, though.
I wanted the get_big_text() method to return the text so that I could pass it somewhere else and "do something" with it when the text comes. The solution was to pass an anonymous function to the method and "tell it" what should be done with it when it does come.
Note the new callback parameter in get_big_text()
from tkinter import *
class Gui:
def __init__(self, root):
tframe = Frame(root)
tframe.pack(side='top')
bframe = Frame(root)
bframe.pack(side='bottom')
self.txt = Text(tframe)
self.txt.insert('0.0', 'Totally foobar')
self.txt.pack()
self.btn = Button(bframe, text='OK')
self.btn.pack()
def get_big_text(self, callback, title='', text=''):
popup = Toplevel(height=160, width=180)
popup.title(title)
txtframe = Frame(popup)
txtframe.pack()
big_text = Text(txtframe)
big_text.insert('0.0',text)
big_text.pack()
btnframe = Frame(popup)
btnframe.pack()
grab_text = Button(btnframe)
grab_text.config(text="Done", command=lambda:callback(big_text.get('0.0', 'end')))
grab_text.pack()
root=Tk()
root.title('Example')
foo = Gui(root)
foo.get_big_text(lambda x:print(x))
root.mainloop()
The general flow for a dialog is to create the window, then call wait_window to wait until the window has been dismissed by the user. Your function can then return whatever you want.
There's a bit of a chicken-and-egg thing going on, in that you need to get the value from the dialog before the dialog is destroyed since the text widget will be destroyed when the toplevel is destroyed. You do this by explicitly managing the destruction of the window (read: get the value before actually destroying the window).
Here's a working example, trying to preserve as much as code as possible but without using a global import:
import Tkinter as tk
class CustomDialog(object):
def __init__(self, parent, title="Enter a paragraph", default_text=""):
self.parent = parent
self.title = title
self.default = default_text
def show(self):
self.popup = tk.Toplevel(self.parent)
self.popup.title(self.title)
txtframe = tk.Frame(self.popup)
txtframe.pack()
self.big_text = tk.Text(txtframe)
self.big_text.insert('1.0',self.default)
self.big_text.pack()
btnframe = tk.Frame(self.popup)
btnframe.pack()
grab_text = tk.Button(btnframe)
grab_text.config(text="Done", command=self.done)
grab_text.pack()
# make sure our "done" method gets called even if the
# user destroys the window
self.popup.wm_protocol("WM_DELETE_WINDOW", self.done)
# wait for the window to be destroyed
root.wait_window(self.popup)
return self.data
def done(self, *args):
# get the data from the window, then destroy
# the window and return to the caller
self.data = self.big_text.get("1.0", "end-1c")
self.popup.destroy()
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
b = tk.Button(self, text="Get Input", command=self.go)
b.pack()
def go(self):
dialog = CustomDialog(self, default_text="totally foobar")
result = dialog.show()
print "result:", result
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
Another option that you have is to pass a callback to your dialog, and tie that callback to the "done" button. That way, whenever the user clicks the button, you execute the callback to do whatever you want with the data before destroying the window.
That is how you implement a non-modal dialog, since you don't necessarily have to destroy the window. Font dialogs are a good example of this, where you might want to keep the dialog open for quite a while, and affect whatever is currently selected.
The effbot site has a decent writeup on dialogs. See http://effbot.org/tkinterbook/tkinter-dialog-windows.htm