Change right click event of tkinter command - python

I want to detect the right click event on tkinter Menu command.
Consider code below.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
menu_button = ttk.Menubutton(root, text="MENU")
menu_button.grid()
m = tk.Menu(menu_button, tearoff=False, activeborderwidth=0)
menu_button["menu"] = m # To avoid garbage collection
m.add_command(label="an option", command=lambda: print("option1"))
m.add_command(label="another option", command=lambda: print("option2"))
root.mainloop()
When I click an option or another option, the commands are called as expected. But want I want to do is catch right click event. Can anyone knows that how can I detect it?

use button.bind("<Button-3>", event). Consider this code:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
button = tk.Button(root, text='right click this')
button.pack()
button.bind("<Button-3>", lambda e: print('You right clicked'))
root.mainloop()

Related

Tkinter window not opening in pycharm

I am eriting code in pycharm with tkinter but the window is not opening. May someone assist?
`
import tkinter
window = tkinter.Tk()
button = tkinter.Button(window, text="Do not press this button! >:-(", width=40)
button.pack(padx=10, pady=10)
`
i tried checking my script for bugs but nothing
This has nothing to do with Pycharm, but with tkinter library and how to use it.
You are missing 2 important stuff:
Button is in ttk.py file inside tkinter library: from tkinter import ttk
Execute the whole script with mainloop
Try this:
import tkinter
from tkinter import ttk # Import ttk file from tkinter library
window = tkinter.Tk()
window.title("Coolest title ever written")
button = ttk.Button(window, text="Do not press this button! >:-(", width=40) # Use Button from the import ttk file
button.pack(padx=10, pady=10)
window.mainloop() # Execute the whole script

Is there away to hide the text inside a button/label in Tkinter?

I'm a Python beginner that trying to learn my way through Tkinter, and I need your help.
Let say I create a simple button like this:
import tkinter as tk
window = tk.Tk()
button = tk.Button(text="Hello World!")
button.pack()
window.mainloop()
Is there a way that I can hide and then display the text again? Given that I can create two more buttons that will do the job of hiding and displaying. I have tried to use button.pack_forget(), but it will hide the entire button instead.
Any help would be appreciated.
To make it look like the buttons text vanishes,you can make the text color as same as the background color via cget method.
import tkinter as tk
def hide_text():
color = button['bg']
button.config(foreground=color, activeforeground=color)
window = tk.Tk()
button = tk.Button(text="Hello World!",command=hide_text)
button.pack()
window.mainloop()
Approach 2 ttk.Button:
import tkinter as tk
from tkinter import ttk
def hide_text():
button.config(text='')
window = tk.Tk()
button = ttk.Button(text="Hello World!",width=100,command=hide_text)
button.pack()
window.mainloop()
Approach3 using style:
import tkinter as tk
from tkinter import ttk
def change_button_style(event):
widget = event.widget
if widget['style'] == 'TButton':
widget.configure(style='VanishedText.TButton')
else:
event.widget.config(style='TButton')
BACKGROUND = '#f0f0f0'
FOREGROUND = '#000000'
window = tk.Tk()
window.configure(bg=BACKGROUND)
style = ttk.Style()
style.theme_use('default')
button = ttk.Button(text="Hello World!",style='VanishedText.TButton')
button.bind('<ButtonPress-1>',change_button_style)#,command=change_button_style
button.pack()
style.map('VanishedText.TButton',
foreground =[('disabled',BACKGROUND),
('!disabled',BACKGROUND),
('pressed',BACKGROUND),
('!pressed',BACKGROUND),
('active',BACKGROUND),
('!active',BACKGROUND)],
background =[('disabled',BACKGROUND),
('!disabled',BACKGROUND),
('pressed',BACKGROUND),
('!pressed',BACKGROUND),
('active',BACKGROUND),
('!active',BACKGROUND)],
focuscolor=[('disabled',BACKGROUND),
('!disabled',BACKGROUND),
('pressed',BACKGROUND),
('!pressed',BACKGROUND),
('active',BACKGROUND),
('!active',BACKGROUND)])
window.mainloop()
You Can Simply Config And Set Text :
import tkinter as tk
from tkinter import ttk
win=tk.Tk()
def hidetext():
button.config(text="")
button=ttk.Button(win,text="FooBar",command=hidetext)
button.pack()
win.mainloop()

How do I destroy a tkinter frame?

I am trying to make a tkinter frame that will contain an entry field and a submit button. When the submit button is pressed, I want to pass the entry string to the program and destroy the frame. After many experiments, I came up with this script:
from tkinter import *
from tkinter import ttk
import time
root = Tk()
entryframe = ttk.Frame(root)
entryframe.pack()
par = StringVar('')
entrypar = ttk.Entry(entryframe, textvariable=par)
entrypar.pack()
submit = ttk.Button(entryframe, text='Submit', command=entryframe.quit)
submit.pack()
entryframe.mainloop()
entryframe.destroy()
parval = par.get()
print(parval)
time.sleep(3)
root.mainloop()
When the "Submit" button is pressed, the parameter value is passed correctly to the script and printed. However, the entry frame is destroyed only after 3 seconds (set by the time.sleep function).
I want to destroy the entry frame immediately.
I have a slightly different version of the script in which the entry frame does get destroyed immediately (although the button itself is not destroyed), but the value of par is not printed:
from tkinter import *
from tkinter import ttk
import time
root = Tk()
entryframe = ttk.Frame(root)
entryframe.pack()
par = StringVar('')
entrypar = ttk.Entry(entryframe, textvariable=par)
entrypar.pack()
submit = ttk.Button(root, text='Submit', command=entryframe.destroy)
submit.pack()
entryframe.mainloop()
# entryframe.destroy()
parval = par.get()
print(parval)
time.sleep(3)
root.mainloop()
How can I get both actions, namely the entry frame destroyed immediately and the value of par printed?
Note 100% sure what you are trying to do but look at this code:
from tkinter import *
from tkinter import ttk
def print_results():
global user_input # If you want to access the user's input from outside the function
# Handle the user's input
user_input = entrypar.get()
print(user_input)
# Destroy whatever you want here:
entrypar.destroy()
submit.destroy()
# If you want you can also destroy the window: root.destroy()
# I will create a new `Label` with the user's input:
label = Label(root, text=user_input)
label.pack()
# Create a tkitner window
root = Tk()
# Create the entry
entrypar = ttk.Entry(root)
entrypar.pack()
# Create the button and tell tkinter to call `print_results` whenever
# the button is pressed
submit = ttk.Button(root, text="Submit", command=print_results)
submit.pack()
# Run tkinter's main loop
# It will stop only when all tkinter windows are closed
root.mainloop()
# Because of the `global user_input` now we can use:
print("Again, user_input =", user_input)
I defined a function which will destroy the entry and the button. It also creates a new label that displays the user's input.
I was able to accomplish what I wanted using the wait_window method. Here is the correct script:
from tkinter import *
from tkinter import ttk
root = Tk()
entryframe = ttk.Frame(root)
entryframe.pack()
entrypar = ttk.Entry(entryframe)
entrypar.pack()
submit = ttk.Button(entryframe, text='Submit', command=entryframe.destroy)
submit.pack()
entrypar.wait_window()
parval = entrypar.get()
print(parval)
close_button = ttk.Button(root, text='Close', command=root.destroy)
close_button.pack()
root.mainloop()
My intention was not fully apparent in my original question, and I apologize for that. Anyway, the answers did put me on the right track, and I am immensely thankful.

Tkinter: Bind <Enter> event to entire window (but not all widgets)

My goal is to bind an Event to the window. For example I want a function called when the mouse pointer enters the window. The code below does this but sadly the function is also called whenever the mouse pointer enters the Button. I tried B.unbind("<Enter>") but it does not work. Any help would be appreciated
import tkinter as tk
root = tk.Tk()
def function(event):
print("Hello World")
B = tk.Button(root, text ="Label")
root.bind("<Enter>",function)
root.geometry("100x100")
B.pack()
root.mainloop()
One way to make this work is to check for event.widget and see if it is the root window, which is a instance of Tk.
import tkinter as tk
root = tk.Tk()
def function(event):
if isinstance(event.widget,tk.Tk): #check if event widget is Tk root window
print("Hello World")
B = tk.Button(root, text ="Label")
root.bind("<Enter>",function)
root.geometry("100x100")
B.pack()
root.mainloop()

Tkinter exit error [duplicate]

How do I end a Tkinter program? Let's say I have this code:
from Tkinter import *
def quit():
# code to exit
root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()
How should I define the quit function to exit my application?
You should use destroy() to close a Tkinter window.
from Tkinter import *
#use tkinter instead of Tkinter (small, not capital T) if it doesn't work
#as it was changed to tkinter in newer Python versions
root = Tk()
Button(root, text="Quit", command=root.destroy).pack() #button to close the window
root.mainloop()
Explanation:
root.quit()
The above line just bypasses the root.mainloop(), i.e., root.mainloop() will still be running in the background if quit() command is executed.
root.destroy()
While destroy() command vanishes out root.mainloop(), i.e., root.mainloop() stops. <window>.destroy() completely destroys and closes the window.
So, if you want to exit and close the program completely, you should use root.destroy(), as it stops the mainloop() and destroys the window and all its widgets.
But if you want to run some infinite loop and don't want to destroy your Tkinter window and want to execute some code after the root.mainloop() line, you should use root.quit(). Example:
from Tkinter import *
def quit():
global root
root.quit()
root = Tk()
while True:
Button(root, text="Quit", command=quit).pack()
root.mainloop()
#do something
See What is the difference between root.destroy() and root.quit()?.
def quit()
root.quit()
or
def quit()
root.destroy()
import tkinter as tk
def quit(root):
root.destroy()
root = tk.Tk()
tk.Button(root, text="Quit", command=lambda root=root:quit(root)).pack()
root.mainloop()
Illumination in case of confusion...
def quit(self):
self.destroy()
exit()
A) destroy() stops the mainloop and kills the window, but leaves python running
B) exit() stops the whole process
Just to clarify in case someone missed what destroy() was doing, and the OP also asked how to "end" a tkinter program.
I think you wrongly understood the quit function of Tkinter. This function does not require you to define.
First, you should modify your function as follows:
from Tkinter import *
root = Tk()
Button(root, text="Quit", command=root.quit).pack()
root.mainloop()
Then, you should use '.pyw' suffix to save this files and double-click the '.pyw' file to run your GUI, this time, you can end the GUI with a click of the Button, and you can also find that there will be no unpleasant DOS window. (If you run the '.py' file, the quit function will fail.)
The usual method to exit a Python program:
sys.exit()
(to which you can also pass an exit status) or
raise SystemExit
will work fine in a Tkinter program.
In case anyone wants to bind their Escape button to closing the entire GUI:
master = Tk()
master.title("Python")
def close(event):
sys.exit()
master.bind('<Escape>',close)
master.mainloop()
The easiest way would be to click the red button (leftmost on macOS and rightmost on Windows).
If you want to bind a specific function to a button widget, you can do this:
class App:
def __init__(self, master)
frame = Tkinter.Frame(master)
frame.pack()
self.quit_button = Tkinter.Button(frame, text = 'Quit', command = frame.quit)
self.quit_button.pack()
Or, to make things a little more complex, use protocol handlers and the destroy() method.
import tkMessageBox
def confirmExit():
if tkMessageBox.askokcancel('Quit', 'Are you sure you want to exit?'):
root.destroy()
root = Tk()
root.protocol('WM_DELETE_WINDOW', confirmExit)
root.mainloop()
you only need to type this:
root.destroy()
and you don't even need the quit() function cause when you set that as commmand it will quit the entire program.
you dont have to open up a function to close you window, unless you're doing something more complicated:
from Tkinter import *
root = Tk()
Button(root, text="Quit", command=root.destroy).pack()
root.mainloop()
In idlelib.PyShell module, root variable of type Tk is defined to be global
At the end of PyShell.main() function it calls root.mainloop() function which is an infinite loop and it runs till the loop is interrupted by root.quit() function. Hence, root.quit() will only interrupt the execution of mainloop
In order to destroy all widgets pertaining to that idlelib window, root.destroy() needs to be called, which is the last line of idlelib.PyShell.main() function.
I normally use the default tkinter quit function, but you can do your own, like this:
from tkinter import *
from tkinter.ttk import *
window = Tk()
window.geometry('700x700') # 700p x 700p screen
def quit(self):
proceed = messagebox.askyesno('Quit', 'Quit?')
proceed = bool(proceed) # So it is a bool
if proceed:
window.quit()
else:
# You don't really need to do this
pass
btn1 = Button(window, text='Quit', command=lambda: quit(None))
window.mainloop()
For menu bars:
def quit():
root.destroy()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=quit)
menubar.add_cascade(label="menubarname", menu=filemenu)
root.config(menu=menubar)
root.mainloop()
I use below codes for the exit of Tkinter window:
from tkinter import*
root=Tk()
root.bind("<Escape>",lambda q:root.destroy())
root.mainloop()
or
from tkinter import*
root=Tk()
Button(root,text="exit",command=root.destroy).pack()
root.mainloop()
or
from tkinter import*
root=Tk()
Button(root,text="quit",command=quit).pack()
root.mainloop()
or
from tkinter import*
root=Tk()
Button(root,text="exit",command=exit).pack()
root.mainloop()
Code snippet below. I'm providing a small scenario.
import tkinter as tk
from tkinter import *
root = Tk()
def exit():
if askokcancel("Quit", "Do you really want to quit?"):
root.destroy()
menubar = Menu(root, background='#000099', foreground='white',
activebackground='#004c99', activeforeground='white')
fileMenu = Menu(menubar, tearoff=0, background="grey", foreground='black',
activebackground='#004c99', activeforeground='white')
menubar.add_cascade(label='File', menu=fileMenu)
fileMenu.add_command(label='Exit', command=exit)
root.config(bg='#2A2C2B',menu=menubar)
if __name__ == '__main__':
root.mainloop()
I have created a blank window here & add file menu option on the same window(root window), where I only add one option exit.
Then simply run mainloop for root.
Try to do it once
Of course you can assign the command to the button as follows, however, if you are making a UI, it is recommended to assign the same command to the "X" button:
def quit(self): # Your exit routine
self.root.destroy()
self.root.protocol("WM_DELETE_WINDOW", self.quit) # Sets the command for the "X" button
Button(text="Quit", command=self.quit) # No ()
There is a simple one-line answer:
Write - exit() in the command
That's it!

Categories

Resources