Automatically Activate Main Window in TkInter - python

Is it possible to automatically activate the main window of a tkinter app? I am using Yosemite on a Mac. When the window comes up, the title bar is grayed out, and I have to click on the window before it will respond to events. The Tk manual says that event generate, "Generates a window event and arranges for it to be processed just as if it had come from the window system." I tried generating a <Button-1> event, but it had no effect. The manual goes on to say, "Certain events, such as key events, require that the window has focus to receive the event properly." I tried focus_force, but it didn't work either.
Is it possible to do what I want? Is this a Mac peculiarity? In the code below, the text changes as the mouse cursor enters and leaves the label, but the app is unresponsive until you click on the window.
import tkinter as tk
root = tk.Tk()
def visit(event):
kilroy['text'] = 'Kilroy was here.'
def gone(event):
kilroy['text'] = 'Kilroy has left the building'
def startup():
root.focus_force()
root.event_generate('<Button-1>')
frame = tk.Frame(root, width=500,height=100)
kilroy = tk.Label(frame, text="Kilroy hasn't been here.", width = 50)
kilroy.grid(row=0,column=0)
frame.grid(row=0,column=0)
kilroy.grid_propagate(0)
frame.grid_propagate(0)
kilroy.bind('<Enter>', visit)
kilroy.bind('<Leave>', gone)
root.after(100,startup)
root.mainloop()

Related

How to pause window to turn on another window?

I use tkinter and CTK:
I have created a page for login and I want to stop or use this page when the user is logged in, I want to show a new window and I want to resume the window when I want? How can I do that, I didn't know how to make it
I'll bite. Here's an example application that opens a second window when the user clicks a button on the main window, and disables interaction with the main window until the second window is closed.
Some configuration has been omitted for brevity, and I'm not using CTk here because I don't know how you've implemented it in your specific application - however, it should be easy enough to modify this example to work with CTk.
import tkinter as tk
from tkinter import ttk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.open_button = ttk.Button(
self,
text='Open 2nd Window',
command=self.modal
)
self.open_button.pack()
def modal(self):
self.window = tk.Toplevel(self) # create new window
# bind a handler for when the user closes this window
self.window.protocol('WM_DELETE_WINDOW', self.on_close)
# disable interaction with the main (root) window
self.attributes('-disabled', True)
self.close_button = ttk.Button(
self.window,
text='Close Modal',
command=self.on_close
)
self.close_button.pack()
def on_close(self):
# re-enable interaction the root window
self.attributes('-disabled', False)
# close the modal window
self.window.destroy()
if __name__ == '__main__':
app = App()
app.mailoop() # run the app
In the future:
Provide code that shows you made a good-faith effort to solve the problem on your own
Don't post the same question multiple times within hours - if you need to make changes, edit the original question
If you mean you want to open up another window to do something before going back to the original window, you should consider using message box. Here is a link that goes over the types of messageboxes: https://docs.python.org/3/library/tkinter.messagebox.html.

Python: How to disable main window while secondary window is open (Tkinter)

I would like to disable the main window of my text adventure program while the character creation window is up. I am relatively new to this. When I try my code below, the main window stays interactable even though the secondary window (creator) is open. There is no error that the console puts out, it just doesn't work is all.
def characterCreator():
global creator
creator = Tk()
creator.title('Character Creator')
creator.geometry('300x400')
while creator.state=='normal':
root.state='disabled'
You should create your creator window as an instance of tkinter.Toplevel() rather than declaring a new instance of Tk() altogether, then you can use grab_set to prevent the user from interacting with the root window while the creator window is open.
import tkinter as tk
root = tk.Tk()
# usual root configs like title and geometry go here
creator = tk.Toplevel(root) # the Toplevel window is a child of the root window
# creator geometry and title and so on go here
creator.grab_set() # keep window on top
if __name__ == '__main__':
root.mainloop()

Create multiple windows using one tkinter button in python

I am opening other windows from a single tkinter button as shown here:
https://www.pythontutorial.net/tkinter/tkinter-toplevel/
The code shown there is
import tkinter as tk
from tkinter import ttk
class Window(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.geometry('300x100')
self.title('Toplevel Window')
ttk.Button(self,
text='Close',
command=self.destroy).pack(expand=True)
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('300x200')
self.title('Main Window')
# place a button on the root window
ttk.Button(self,
text='Open a window',
command=self.open_window).pack(expand=True)
def open_window(self):
window = Window(self)
window.grab_set()
if __name__ == "__main__":
app = App()
app.mainloop()
If I run this program, it is not possible to hit the "Open a window" button twice to get two Toplevel instances. I would like to get as many instances as I like to with only one button. Is this possible somehow?
Consider this line of code:
window.grab_set()
This is setting a grab on the first window that is created. That means that all events from both the keyboard and the mouse are funneled to the first window that is created. That means you can no longer click on the button in the root window until the grab has been removed. Note that if the window is destroyed, the grab is automatically removed.
Grabs are typically used when creating a modal dialog -- a dialog which requires user input before the program can continue. By doing a grab, you insure that the user can't interact with the main program until they've interacted with the dialog.
The solution is simple: remove the call to window.grab_set() if your goal is to be able to open multiple windows which can all be used at the same time.
Simply remove window.grab_set(). The grab_set() method routes all events for this application to this widget. Whatever events generated like button-click or keypress is directed to another window.
def open_window(self):
window = Window(self)

Disable button in Tkinter (Python)

Hi , I have some question to ask
I just want to disable the button when i start my program
in attached image, it looks like the button is already disabled ,but its response to my click event or keyboard event
What should i do ?
Thank you for all answer
from Tkinter import *
def printSomething(event):
print("Print")
#Start GUI
gui = Tk()
gui.geometry("800x500")
gui.title("Button Test")
mButton = Button(text="[a] Print",fg="#000",state="disabled")
mButton.place(x=5,y=10)
mButton.bind('<Button-1>',printSomething)
gui.bind('a',printSomething)
gui.mainloop()
You need to unbind the event. state="disabled"/state=DISABLED makes button disabled but it doesn't unbind the event. You need to unbind the corresponding events to achieve this goal. If you want to enable the button again then you need to bind the event again. Like:
from Tkinter import *
def printSomething(event):
print("Print")
#Start GUI
gui = Tk()
gui.geometry("800x500")
gui.title("Button Test")
mButton = Button(text="[a] Print",fg="#000",state="disabled")
mButton.place(x=5,y=10)
mButton.bind('<Button-1>',printSomething)
mButton.unbind("<Button-1>") #new line added
gui.bind('a',printSomething)
gui.mainloop()

Close a tkinter window after a period of time

I have a piece of Python code that is supposed to open a new window for a period of time and then close the window. The window is triggered by clicking a button. Here is the basics of what I have.
def restore(self):
self.restore = Toplevel()
message = "Select an available Backup to Restore to."
Label(self.restore, text=message).pack()
# We then create and entry widget, pack it and then
# create two more button widgets as children to the frame.
os.chdir('.')
for name in os.listdir("."):
if os.path.isdir(name):
self.button = Button(self.restore, text=name,command=self.restoreCallBack)
self.button.pack(side=BOTTOM,padx=10)
def restoreCallBack(self):
self.restoreCB = Toplevel()
message = "Please wait while the database is restored..."
Label(self.restoreCB, text=message, padx=100, pady=20).pack()
time.sleep(5)
self.restore.destroy()
self.restoreCB.destroy()
I need the restoreCallBack window to be displayed for 5 seconds, then the windows to close. Thanks!
Have a look at the after method. e.g.:
widget.after(5000,callback)
You shouldn't use sleep in (the main thread of) a GUI -- The entire thing will just freeze.

Categories

Resources