How to select one chech menu at one time in tkinter python - python

I created a menu with checkbutton in my tkinter program but i wanted to select only one menu at one time below is code
def menu(self):
menubar = Menu(bg="black",fg="white")
self.file_menu = Menu(menubar,tearoff=0)
self.file_menu.add_command(label="Save",command=self.Save)
self.edit_menu = Menu(menubar, tearoff=0)
self.edit_menu.add_command(label="Undo",command=self.Undo)
self.edit_menu.add_command(label="Redo",command=self.Redo)
self.edit_menu.add_separator()
self.edit_menu.add_command(label="Cut",command=self.Cut)
self.edit_menu.add_command(label="Copy",command=self.Copy)
self.edit_menu.add_command(label="Paste",command=self.Paste)
self.edit_menu.add_separator()
self.edit_menu.add_command(label="Find",command=self.Find)
self.edit_menu.add_command(label="Replace",command=self.Replace)
self.Run_menu = Menu(menubar,tearoff=0)
self.Run_menu.add_command(label="Run",command=self.Run)
Language_menu = Menu(tearoff=0)
Language_menu.add_checkbutton(label="Python")
Language_menu.add_checkbutton(label="Java")
self.Run_menu.add_cascade(label="Language ",menu=Language_menu)
menubar.add_cascade(label="File",menu=self.file_menu)
menubar.add_cascade(label="Edit",menu=self.edit_menu)
menubar.add_cascade(label="Run",menu=self.Run_menu)
self.config(menu=menubar)
i wants that if i will select python or java any one of them then other automatically got deselect
thanks in advance

If you must use check buttons but want these to function such that clicking one unchecks the other then you can do so by creating variables to track the state of the check buttons and updating these as appropriate when clicked.
Menu with check buttons: Here is an example of this:
import tkinter as tk
parent = tk.Tk()
# create variables to track the state of check buttons
check_python = tk.BooleanVar()
check_java = tk.BooleanVar()
# handle the check buttons being clicked by unchecking others
def check_python_clicked():
check_python.set(True)
check_java.set(False)
def check_java_clicked():
check_python.set(False)
check_java.set(True)
# create and display the menu
menu_bar = tk.Menu(bg="black", fg="white")
run_menu = tk.Menu(tearoff=0)
language_menu = tk.Menu(run_menu)
language_menu.add_checkbutton(label='Python', variable=check_python, command=check_python_clicked)
language_menu.add_checkbutton(label='Java', variable=check_java, command=check_java_clicked)
run_menu.add_cascade(label='Language', menu=language_menu)
menu_bar.add_cascade(label="Run", menu=run_menu)
parent.config(menu=menu_bar)
parent.mainloop()
Menu with radio buttons: However, you can use radio buttons and achieve the same functionality with less code. This would be a better approach in this case as your options are mutually exclusive:
import tkinter as tk
parent = tk.Tk()
menu_bar = tk.Menu(bg="black", fg="white")
run_menu = tk.Menu(tearoff=0)
language_menu = tk.Menu(run_menu)
language_menu.add_radiobutton(label='Python')
language_menu.add_radiobutton(label='Java')
run_menu.add_cascade(label='Language', menu=language_menu)
menu_bar.add_cascade(label="Run", menu=run_menu)
parent.config(menu=menu_bar)
parent.mainloop()

Related

Get dynamically which button uses function

I have a question about buttons and binds, but it's better if I show you.
from tkinter import Tk,Button
root = Tk()
startbutton = Button(root,text="start button")
pingbutton = Button(root,text="ping button")
startbutton.pack()
pingbutton.pack()
def startenterbind(e):
startbutton.config(relief='sunken')
def startleavebind(e):
startbutton.config(relief='raised')
def pingenterbind(e):
pingbutton.config(relief='sunken')
def pingleavebind(e):
pingbutton.config(relief='raised')
startbutton.bind("<Enter>", startenterbind)
startbutton.bind("<Leave>", startleavebind)
pingbutton.bind("<Enter>", pingenterbind)
pingbutton.bind("<Leave>", pingleavebind)
root.mainloop()
This is my code, now I am wondering, is there a better way to do this?
Maybe it's possible to get which button was hovered dynamically, to then change the button that was hovered?
This is so I can use one function for multiple buttons, while only affecting the one being <Enter>'d or <Leave>'d?
You can reuse an event handler function by making use of the event object they are passed which has an attribute telling you the widget that triggered it.
from tkinter import Tk,Button
root = Tk()
startbutton = Button(root,text="start button")
pingbutton = Button(root,text="ping button")
startbutton.pack()
pingbutton.pack()
def startenterbind(event):
event.widget.config(relief='sunken')
def startleavebind(event):
event.widget.config(relief='raised')
startbutton.bind("<Enter>", startenterbind)
startbutton.bind("<Leave>", startleavebind)
pingbutton.bind("<Enter>", startenterbind)
pingbutton.bind("<Leave>", startleavebind)
root.mainloop()
You could go a bit further by writing a single function that simply toggled the state of the button whenever it was called. One way that could be accomplished is by making the new relief type depend on what it currently is which can be determined by calling the universal widget cget() method:
def enterleavebind(event):
new_relief = 'sunken' if event.widget.cget('relief') == 'raised' else 'raised'
event.widget.config(relief=new_relief)
startbutton.bind("<Enter>", enterleavebind)
startbutton.bind("<Leave>", enterleavebind)
pingbutton.bind("<Enter>", enterleavebind)
pingbutton.bind("<Leave>", enterleavebind)

How to Refresh a Tab in Tkinter after Interacting with a Database?

I have a python script for teachers that works very well on my terminal and I'm trying to use Tkinter so I can share this script with other people. In the script, the user uploads a file and other information to an SQLite database.
Below is part of the script that shows just the content for the 1st tab (of 3). The problem is that when people interact with the database the tab needs to get refreshed to show something has happened and that the list of files in the database has changed.
Everything I've read shows you need a button to refresh. But that is not user-friendly. What people want to do is upload a file and then see that file in the list. Is this possible with Tkinter and if so how?
class AppWindow():
my_list = [4]
def __init__(self, parent):
global my_list
# Create the window
self.window = parent
self.window.geometry("700x600")
#self.center_window()
self.window.title("Test app")
# Create a text label and place it in the window
self.hello_label = tk.Label(self.window, text="Hello world!")
self.hello_label.place(x=20, y=20)
# Create 3 tabs
self.tab_container = tk.Frame(self.window)
self.tab_container.place(x=0,y=0,width=700,height=400)
self.tabs = ttk.Notebook(self.tab_container)
self.tab_2 = tk.Frame(self.tabs)
self.tabs.add(self.tab_2, text="Parameters")
self.tabs.place(x=0,y=0,height=400,width=700)
# Content for tab 2
self.label2 = tk.Label(self.tab_2, text="")
self.label201=tk.Label(self.tab_2, text="Put in your target GPA")
self.label201.place(x=50, y=50)
btn1 = tk.Button(self.tab_2,text="Target GPA", command=self.getGPA)
btn1.place(x=50, y=80)
for lst in self.my_list:
btn99=tk.Button(self.tab_2,text=lst)
btn99.grid()
def getGPA(self):
userInput = sd.askstring('User Input','Enter target GPA')
self.my_list.append(userInput)
if __name__ == "__main__":
root = tk.Tk()
app = AppWindow(root)
root.mainloop()
This is merely a guess because of the all the reasons I've already mentioned in comments under your question. Generally speaking, to update or what you call "refresh" a tab requires adding, changing, or deleting the widgets you put on it.
The code below is based what's currently in your code. Every time the Target GP button is clicked another Button is added to the self.tab_2 frame as well as appended to my_list. Changing the widgets doesn't have to be triggered by clicking on a button, it could be the result of some other event (such as the completion of a file upload in the background for example).
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.simpledialog as sd
class AppWindow():
def __init__(self, parent):
# Create the window
self.window = parent
self.window.geometry("700x600")
#self.center_window()
self.window.title("Test app")
# Create and initialize data list.
self.my_list = [4]
# Create a text label and place it in the window
self.hello_label = tk.Label(self.window, text="Hello world!")
self.hello_label.place(x=20, y=20)
# Create 3 tabs
self.tab_container = tk.Frame(self.window)
self.tab_container.place(x=0, y=0, width=700, height=400)
self.tabs = ttk.Notebook(self.tab_container)
self.tab_2 = tk.Frame(self.tabs)
self.tabs.add(self.tab_2, text="Parameters")
self.tabs.place(x=0, y=0, height=400, width=700)
# Content for tab 2
self.label201 = tk.Label(self.tab_2, text="Put in your target GPA")
self.label201.place(x=50, y=50)
btn1 = tk.Button(self.tab_2, text="Target GPA", command=self.getGPA)
btn1.place(x=50, y=80)
# Create a Button for each item currently in list.
for item in self.my_list:
btn = tk.Button(self.tab_2, text=item)
btn.grid()
def getGPA(self):
userInput = sd.askstring('User Input', 'Enter target GPA')
if userInput is None: # User closed the dialog or clicked Cancel?
return
self.my_list.append(userInput)
btn = tk.Button(self.tab_2, text=userInput) # Create another Button.
btn.grid()
if __name__ == "__main__":
root = tk.Tk()
app = AppWindow(root)
root.mainloop()

Why does my selection callback get called on my second Listbox?

from tkinter import *
from tkinter.ttk import *
root = Tk()
listbox = None
listboxMultiple = None
listboxStr = None
listboxMultipleStr = None
def main():
global root
global listboxStr
global listboxMultipleStr
global listbox
global listboxMultiple
root.protocol("WM_DELETE_WINDOW", exitApplication)
root.title("Title Name")
root.option_add('*tearOff', False) # don't allow tear-off menus
root.geometry('1600x300')
listboxStr = StringVar()
listboxStr.set("ABCD")
listbox = Listbox(root, name="lb1", listvariable=listboxStr, width=120)
listbox.pack(side=LEFT)
listbox.bind("<<ListboxSelect>>", selectListItemCallback)
listboxMultipleStr = StringVar()
listboxMultipleStr.set("")
listboxMultiple = Listbox(root, name="lb2", listvariable=listboxMultipleStr, width=120)
listboxMultiple.pack(side=LEFT)
root.mainloop()
def selectListItemCallback(event):
global listboxMultipleStr
global listbox
global listboxMultiple
print("event.widget is {} and listbox is {} and listboxMultiple is {}\n".format(event.widget, listbox, listboxMultiple))
selection = event.widget.curselection()
listboxMultipleStr.set("")
if selection:
index = selection[0]
data = event.widget.get(index)
newvalue = "{}\n{}".format(data,"SOMETHING")
print("selected \"{}\"\n".format( data ))
print("newvalue is \"{}\"\n".format( newvalue ))
listboxMultiple.insert(END, "{}".format(data))
listboxMultiple.insert(END, "SOMETHING")
#listboxMultipleStr.set( newvalue )
else:
pass
def exitApplication():
global root
root.destroy()
if __name__ == "__main__":
main()
Using python3 on Windows 7. I've setup a callback "selectListItemCallback" for one of my two listbox widgets. And yet, when I click on the text in "lb1" it works as expected, I update "lb2" with the same selected text plus I add another line to "lb2".
The issue is, when I then select the item in "lb2", it still calls the callback and the event.widget is "lb1" and not "lb2".
My intent is to have a list of items in 'lb1' and when I select any of them, then 'lb2' gets filled with info related to the selected 'lb1' item. And, I don't want a selection callback invoked in my 'lb2' widget.
Can you see what I'm doing wrong that could be causing this strange behavior?
Thank you.
I've posted the code; and this does run on my Windows 7 machine using python3. Python 3.8.6 to be exact.
It is because the event fires when the first list box loses the selection when you click on the other list box. The event fires whenever the selection changes, not just when it is set.
If you don't want the first listbox to lose its selection when you click in the second listbox, set exportselection to False for the listboxes. Otherwise, tkinter will only allow one to have a selection at a time.

How to add hover feature for text description on a Tkinter button?

I want to add a hover feature on a Tkinter button where if the user hovers the mouse cursor then description text displays. I also want to add some delay for that description to appear so that it would not be intrusive.
I can try using the "<Enter>" and "<Leave>" binding of the button to a function and make some "Label" appear in some corner of the app. But this approach may not be the most elegant.
This can be done very easily with tkinter. By adding Enter and Leave events to whatever you want to add a tooltip to, we can easily show/hide whatever we want, wherever we want. In my example I use a stripped-down tk.Toplevel so we can have a simple fade animation, and the tooltip wont be confined to the root window.
#widgets.py
import tkinter as tk, tkinter.ttk as ttk
from typing import Union
Widget = Union[tk.Widget, ttk.Widget]
class ToolTip(tk.Toplevel):
#amount to adjust fade by on every animation frame
FADE_INC:float = .07
#amount of milliseconds to wait before next animation state
FADE_MS :int = 20
def __init__(self, master, **kwargs):
tk.Toplevel.__init__(self, master)
#make window invisible, on the top, and strip all window decorations/features
self.attributes('-alpha', 0, '-topmost', True)
self.overrideredirect(1)
#style and create label. you can override style with kwargs
style = dict(bd=2, relief='raised', font='courier 10 bold', bg='#FFFF99', anchor='w')
self.label = tk.Label(self, **{**style, **kwargs})
self.label.grid(row=0, column=0, sticky='w')
#used to determine if an opposing fade is already in progress
self.fout:bool = False
def bind(self, target:Widget, text:str, **kwargs):
#bind Enter(mouseOver) and Leave(mouseOut) events to the target of this tooltip
target.bind('<Enter>', lambda e: self.fadein(0, text, e))
target.bind('<Leave>', lambda e: self.fadeout(1-ToolTip.FADE_INC, e))
def fadein(self, alpha:float, text:str=None, event:tk.Event=None):
#if event and text then this call came from target
#~ we can consider this a "fresh/new" call
if event and text:
#if we are in the middle of fading out jump to end of fade
if self.fout:
self.attributes('-alpha', 0)
#indicate that we are fading in
self.fout = False
#assign text to label
self.label.configure(text=f'{text:^{len(text)+2}}')
#update so the proceeding geometry will be correct
self.update()
#x and y offsets
offset_x = event.widget.winfo_width()+2
offset_y = int((event.widget.winfo_height()-self.label.winfo_height())/2)
#get geometry
w = self.label.winfo_width()
h = self.label.winfo_height()
x = event.widget.winfo_rootx()+offset_x
y = event.widget.winfo_rooty()+offset_y
#apply geometry
self.geometry(f'{w}x{h}+{x}+{y}')
#if we aren't fading out, fade in
if not self.fout:
self.attributes('-alpha', alpha)
if alpha < 1:
self.after(ToolTip.FADE_MS, lambda: self.fadein(min(alpha+ToolTip.FADE_INC, 1)))
def fadeout(self, alpha:float, event:tk.Event=None):
#if event then this call came from target
#~ we can consider this a "fresh/new" call
if event:
#indicate that we are fading out
self.fout = True
#if we aren't fading in, fade out
if self.fout:
self.attributes('-alpha', alpha)
if alpha > 0:
self.after(ToolTip.FADE_MS, lambda: self.fadeout(max(alpha-ToolTip.FADE_INC, 0)))
#main.py ~ EXAMPLE USAGE OOP
import tkinter as tk
from widgets import ToolTip
class Root(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
#instantiate ToolTip
tt = ToolTip(self)
#create first button and bind a tooltip to it
btn = tk.Button(self, text='hover')
btn.grid(column=0, row=0)
tt.bind(btn, 'first button is hovered')
#create second button and bind a tooltip to it
btn2 = tk.Button(self, text='hover2')
btn2.grid(column=1, row=0)
tt.bind(btn2, 'second button is hovered')
if __name__ == "__main__":
root = Root()
root.title("ToolTip Example")
root.mainloop()
#main.py ~ EXAMPLE USAGE PROCEDURAL
import tkinter as tk
from widgets import ToolTip
if __name__ == "__main__":
root = tk.Tk()
root.title("ToolTip Example")
#instantiate ToolTip
tt = ToolTip(root)
#create first button and bind a tooltip to it
btn = tk.Button(root, text='hover')
btn.grid(column=0, row=0)
tt.bind(btn, 'first button is hovered')
#create second button and bind a tooltip to it
btn2 = tk.Button(root, text='hover2')
btn2.grid(column=1, row=0)
tt.bind(btn2, 'second button is hovered')
root.mainloop()
Here is a small snippet using Pmw (python mega widgets) for the tool tips.
Firstly start by installing it:
pip install Pmw
Then here is a snippet to understand what Pmw can do:
from tkinter import *
import Pmw
root = Tk()
Pmw.initialise(root) #initializing it in the root window
l = Label(root,text='Random Text')
l.pack()
b = Button(root,text='Hover me')
b.pack()
tooltip_1 = Pmw.Balloon(root) #Calling the tooltip
tooltip_1.bind(b,'This is the hover Text\nHope you get an idea of whats going on here.') #binding it and assigning a text to it
root.mainloop()
Hope this gives you a better idea. Keep in mind that Pmw could create a mess while converting the py to an exe later(if you have any intentions to). There is a way around in tho.
Cheers

ComboBox clears unrelated ListBox tkinter python

I have a really simple GUI program written in python with tkinter:
from Tkinter import *
from ttk import Combobox
class TestFrame(Frame):
def __init__(self, root, vehicles):
dropdownVals = ['test', 'reallylongstring', 'etc']
listVals = ['yeaaaah', 'mhm mhm', 'untz untz untz', 'test']
self.dropdown = Combobox(root, values=dropdownVals)
self.dropdown.pack()
listboxPanel = Frame(root)
self.listbox = Listbox(listboxPanel, selectmode=MULTIPLE)
self.listbox.grid(row=0, column=0)
for item in listVals:
self.listbox.insert(END, item) # Add params to list
self.scrollbar = Scrollbar(listboxPanel, orient=VERTICAL)
self.listbox.config(yscrollcommand=self.scrollbar.set) # Connect list to scrollbar
self.scrollbar.config(command=self.listbox.yview) # Connect scrollbar to list
self.scrollbar.grid(row=0, column=1, sticky=N+S)
listboxPanel.pack()
self.b = Button(root, text='Show selected list values', command=self.print_scroll_selected)
self.b.pack()
root.update()
def print_scroll_selected(self):
listboxSel = map(int, self.listbox.curselection()) # Get selections in listbox
print '=========='
for sel in listboxSel:
print self.listbox.get(sel)
print '=========='
print ''
# Create GUI
root = Tk()
win = TestFrame(root, None)
root.mainloop();
The GUI looks like this:
I click in a few items in the ListBox and hit the button.
The output I get is as expected:
==========
untz untz untz
==========
==========
yeaaaah
untz untz untz
==========
I now choose a value from the ComboBox and suddenly the selection in the ListBox is gone. Hitting the button shows that no value is selected in the ListBox:
==========
==========
My question is: why does the selection of a ComboBox item clear the selection of the ListBox? They are in no way related so this bug really puzzles me!
I finally found the answer. I will leave this question here in case someone else finds it.
The problem was not in the ComboBox but in the ListBox. This becomes clear if I use two (unrelated) ListBoxes. With two ListBoxes the selection will clear when the focus is changed.
From this question and its accepted answer I found that adding exportselection=0 to a ListBox disables the X selection mechanism where the selection is exported.
From effbot listbox about X selection mechanism: selects something in one listbox, and then selects something in another, the original selection disappears.

Categories

Resources