This is a followup to my question here. I'm trying to use ttk.OptionMenu to enhance the look and feel of a dropdown menu. But as noted in the post here, "A ttk optionmenu widget starts out with all of its values in the dropdown. Upon selecting any value, the first value in the list vanishes, never to reappear..." The workaround as suggested in that post is to add an empty item to the list. In my case, since I am using a dictionary, adding '':[] as the first item in the dictionary fixed the problem. Is this the only solution? I hate to introduce an artifact into my dictionary. Here's the code:
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
class App:
def __init__(self, master):
master.title("Continental System")
self.dict = {'':[], 'Asia': ['Japan', 'China', 'Malasia'],
'Europe': ['Germany', 'France', 'Switzerland'],
'Africa': ['Nigeria', 'Kenya', 'Ethiopia']}
self.frame1 = ttk.Frame(master)
self.frame1.pack()
self.frame2 = ttk.Frame(master)
self.frame2.pack()
self.variable_a = tk.StringVar()
self.variable_b = tk.StringVar()
self.variable_a.trace('w', self.updateoptions)
self.optionmenu_a = ttk.OptionMenu(self.frame1, self.variable_a, *self.dict.keys())
self.variable_a.set("Asia")
self.optionmenu_a.grid(row = 0, column = 0)
self.optionmenu_b = ttk.OptionMenu(self.frame1, self.variable_b, '')
self.optionmenu_b.grid(row = 0, column = 1)
self.btn = ttk.Button(self.frame2 , text="Submit", width=8, command=self.submit)
self.btn.grid(row=0, column=1, padx=20, pady=20)
def updateoptions(self, *args):
countries = self.dict[self.variable_a.get()]
self.variable_b.set(countries[0])
menu = self.optionmenu_b['menu']
menu.delete(0, 'end')
for country in countries:
menu.add_command(label=country, command=lambda country=country: self.variable_b.set(country))
def submit(self, *args):
var1 = self.variable_a.get()
var2 = self.variable_b.get()
if messagebox.askokcancel("Confirm Selection", "Confirm your selection: " + var1 + ' ' + var2 + ". Do you wish to continue?"):
print(var1, var2)
def set_window(self, *args):
w = 800
h = 500
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root = tk.Tk()
app = App(root)
app.set_window()
root.mainloop()
Also I am getting some error messages including AttributeError: 'App' object has no attribute 'optionmenu_b'which seemed to have been resolved in the answer to my first question above.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
File "C:\Python34\tk1_version2.py", line 32, in updateoptions
menu = self.optionmenu_b['menu']
AttributeError: 'App' object has no attribute 'optionmenu_b'
Python Version 3.4.1
That post you quote is incorrect. You do not need to put a space as the first item in the list. The signature of the ttk.OptionMenu command requires a default value as the first argument after the variable name.
You do not need to add an empty item to your dictionary. You do need to add a default value when you create the optionmenu:
self.optionmenu_a = ttk.OptionMenu(self.frame1, self.variable_a, "Asia", *self.dict.keys())
A slightly better solution would be to get the list of keys and save them to a list. Sort the list, and then use the first element of the list as the default:
options = sorted(self.dict.keys())
self.optionmenu_a = ttk.OptionMenu(self.frame1, self.variable_a, options[0], *options)
The reason you get the error is because you have a trace on the variable which calls a function that references self.optionmenu_b, but you are initially setting that variable before you create self.optionmenu_b. The simple solution is to create the second menu first.
self.optionmenu_b = ttk.OptionMenu(...)
self.optionmenu_a = ttk.OptionMenu(...)
Related
I'm trying to create a tkinter GUI that will be used to communicate with a microcontroller.
I want to create a bunch of Button - Entry pairs that each will send a command to the microcontroller together with the input of each Entry (formatted specific to that command).
I want to create the buttons by iterating over a list which contain the button name and a formatting function for the Entry widget.
See the code below for an example.
import tkinter as tk
root = tk.Tk()
class ButtonEntryFrame():
def __init__(self, parent, params, txtVar) -> None:
self.txt = params[0]
self.fn = params[1]
self.txtVar = txtVar
self.frame = tk.Frame(parent)
self.button = tk.Button(self.frame, text=self.txt, command=self.fn(self.txtVar))
self.entry = tk.Entry(self.frame, textvariable=self.txtVar)
self.button.pack(side=tk.LEFT)
self.entry.pack()
self.frame.grid()
frameInput = tk.Frame(root)
frameInput.pack(side=tk.LEFT)
inputFunctions = [
('Func A', lambda x: print(f"startMotor {x} 0 1")),
('Func B', lambda x: print(f"stopMotor")),
('Func C', lambda x: print(f"increaseSpeed 100 {x} 3"))]
frames = []
for i, params in enumerate(inputFunctions):
txtVar = tk.StringVar()
f = ButtonEntryFrame(frameInput, params, txtVar)
frames.append(f)
root.mainloop()
The code above does not work as I intend it to work. When I run it the lambdas are executed and printed directly. I understand why.
Is it possible to achieve what I want?
You must do:
self.button = tk.Button(self.frame, text=self.txt, command=lambda: self.fn(self.txtVar))
I added the lambda else self.fnis immediately called.
I am trying to clean up my code. I currently have a long list of labels that are 'printed' if a certain condition is met. For example:
if 0000:
output_0 = Label(frame_20, text="Condition 0 costs $15",
bg='white', padx=10, pady=10).grid(column=0,row=0)
if 0001:
output_1 = Label(frame_20, text="Condition 1 costs $20",
bg='white', padx=10, pady=10).grid(column=0,row=0)
Ideally what I want is to separate the cost variable and the text entirely from the Label so that my code looks something like this:
if 0000:
cost_0 = 15
outputText = ("Condition 0 costs %d", cost_0)
if 0001:
cost_1 = 20
outputText = ("Condition 1 costs %d", cost_1)
output_x = Label(frame_20, vartext=outputText,
bg='white', padx=10, pady=10).grid(comumn=0,row=0)
I assume you are asking for some feature that you don't know yet - and also guessing you have way more conditions than your example.
For string formmating, use f-string. That is easiest, yet robust way to do so. For more details, check python online docs.
In a nutshell, it's used like this:
a = 10
f" <any_text> {a} <even_more_text> "
About dynamic widget adding, forget about naming every label widget you created. Just iterate thru condition pairs and generate widgets, then store those in list.
import tkinter
from typing import Iterable, Tuple, List
# List your conditions - expressions, bool, lambda, whatever in pair with associated value
conditions = (10 == 6, 15), (True, 20), (5, 25)
class App(tkinter.Frame):
def __init__(self, root_):
super().__init__(root_)
self.root = root_
self.pack()
# anything to store the reference - list, class, anything
self.labels: List[tkinter.Label] = []
def generate_labels(self, conditions_: Iterable[Tuple[bool, int]]):
for idx, (condition, price_tag) in enumerate(conditions_):
if condition:
self.labels.append(tkinter.Label(self, text=f"Condition {idx} costs ${price_tag}"))
for label in self.labels:
label.pack()
root = tkinter.Tk()
app_reference = App(root)
app_reference.generate_labels(conditions)
root.mainloop()
And there's no such parameter vartext in tkinter.Label. I think you wanted to type textvariable.
If what you wanted is to have a state and checking if it matches the condition, then this will do:
import tkinter
class App(tkinter.Frame):
def __init__(self, root_):
super().__init__(root_)
self.root = root_
self.pack()
self.solution_dict = {"0000": 15, "0001": 20, "0002": 25}
self.label: tkinter.Label = None
def get_solution(self, condition: str):
if condition in self.solution_dict.keys():
self.label = tkinter.Label(self, text=f"Condition {condition} costs ${self.solution_dict[condition]}")
self.label.pack()
root = tkinter.Tk()
app_reference = App(root)
app_reference.get_solution("0001")
root.mainloop()
If there's more than one condition matching, try if dictionary key is inside the condition string.
import tkinter
from typing import List
class App(tkinter.Frame):
def __init__(self, root_):
super().__init__(root_)
self.root = root_
self.pack()
self.solution_dict = {"0000": 15, "0001": 20, "0002": 25}
self.labels: List[tkinter.Label] = []
def get_solution(self, condition: str):
for key in self.solution_dict.keys():
if key in condition:
widget = tkinter.Label(self, text=f"Condition {key} costs ${self.solution_dict[key]}")
widget.pack()
self.labels.append(widget)
root = tkinter.Tk()
app_reference = App(root)
app_reference.get_solution("0001 & 0002")
root.mainloop()
I am working on a project. I set a toplevel, a listbox and textbox on the toplevel. I want to have a function that is called when I click on one of the elements of the list, and then I want to get the index of the selected element, and update the textbox. Any ideas?
This is the code I have, but it doesn't do what I want it to do:
def helpInitialize():
help = Toplevel()
help.title("Help")
help.geometry("1000x650")
help.resizable(0,0)
helpFiles= []
listy = Scrollbar(help)
listy.place(x=143, y=20, height=565)
listHelp = Listbox(help, height=35, width=20)
listHelp.place(x=20, y=20)
listHelp.config(yscrollcommand=listy.set)
listy.config(command=listHelp.yview)
texty = Scrollbar(help)
texty.place(x= 977, y= 20, height = 565)
textx = Scrollbar(help,orient= HORIZONTAL)
textx.place(x = 175, y= 583, width = 800)
helpText = Text(help, bg="white", height=35, width=100)
helpText.place(x=175, y=20)
helpText.configure(state="disabled")
helpText.config(yscrollcommand=texty.set, xscrollcommand=textx.set)
texty.config(command=helpText.yview)
textx.config(command=helpText.xview)
listHelp.bind("<Button-1>", theFunction)
def theFunction(event):
print(listHelp.get(listHelp.curselection()))
In your case, you can use lambda to pass the Listbox and Text widgets to the function:
listHelp.bind('<Button-1>', lambda e: theFunction(e.widget, helpText))
Modify theFunction():
def theFunction(listbox, textbox):
index = listbox.curselection()[0]
value = listbox.get(index)
textbox.insert(tk.END, str(value)+'\n')
textbox.see(tk.END)
Typically, I'll put my tkinter objects into a class. It makes it much easier to share objects between functions. Here is an example of how that could be achieved with the sample code you provided.
from tkinter import Toplevel, Scrollbar, Listbox, Text, HORIZONTAL, END
class Help:
def __init__(self):
self.help = Toplevel()
self.help.title("Help")
self.help.geometry("1000x650")
self.help.resizable(0,0)
self.helpFiles = ['Test ' + str(i) for i in range(100)]
self.listy = Scrollbar(self.help)
self.listy.place(x=143, y=20, height=565)
self.listHelp = Listbox(self.help, height=35, width=20)
self.listHelp.place(x=20, y=20)
self.listHelp.config(yscrollcommand=self.listy.set)
self.listy.config(command=self.listHelp.yview)
for item in self.helpFiles:
self.listHelp.insert(END, item)
self.texty = Scrollbar(self.help)
self.texty.place(x= 977, y= 20, height = 565)
self.textx = Scrollbar(self.help, orient= HORIZONTAL)
self.textx.place(x = 175, y= 583, width = 800)
self.helpText = Text(self.help, bg="white", height=35, width=100)
self.helpText.place(x=175, y=20)
self.helpText.configure(state="disabled")
self.helpText.config(yscrollcommand=self.texty.set, xscrollcommand=self.textx.set)
self.texty.config(command=self.helpText.yview)
self.textx.config(command=self.helpText.xview)
self.listHelp.bind("<<ListboxSelect>>", self.theFunction)
def theFunction(self, event):
print(self.listHelp.get(self.listHelp.curselection()))
# your code here
if __name__ == '__main__':
test = Help()
test.help.mainloop()
Additionally I changed your function binding from <Button-1> to <<ListboxSelect>>. I believe that one has the functionality you desired.
I am trying to bind this function self.copyTextToClipboard(self,t) to multiple different trees to make it more flexible (please see binding below).
from tkinter.ttk import Treeview
from tkinter import *
class App:
def __init__(self, master):
self.master = master
frame = Frame(master)
master.geometry("{}x{}".format(master.winfo_screenwidth() - 100, master.winfo_screenheight() - 100))
master.resizable(False, False)
self.leftFrame = Frame(master, bg="#DADADA", width=375, relief=SUNKEN)
self.leftFrame.pack_propagate(0)
self.leftFrame.pack(side=LEFT, fill=Y, padx=1)
# This table (TreeView) will display the partitions in the tab
self.partitionsOpenDiskTree = Treeview(self.leftFrame, columns=("#"), show="headings", selectmode="browse", height=23)
yscrollB = Scrollbar(self.leftFrame)
yscrollB.pack(side=RIGHT, fill=Y)
self.partitionsOpenDiskTree.column("#", width=50)
self.partitionsOpenDiskTree.heading("#", text="#")
self.partitionsOpenDiskTree.configure(yscrollcommand=yscrollB.set)
# Bind left click on text widget to copy_text_to_clipboard() function
self.partitionsOpenDiskTree.bind("<ButtonRelease-1>", lambda t=self.partitionsOpenDiskTree: self.copyTextToClipboard(self,t))
# Adding the entries to the TreeView
for i in range(3):
self.partitionsOpenDiskTree.insert("", "end", i, values=(i), tags=str(i))
self.partitionsOpenDiskTree.pack(anchor=NW, fill=Y)
#todo: figure out where this is getting called and put in tree
def copyTextToClipboard(self, tree, event=None):
print(type(tree))
# triggered off left button click on text_field
root.clipboard_clear() # clear clipboard contents
textList = tree.item(tree.focus())["values"]
line = ""
for text in textList:
if line != "":
line += ", " + str(text)
else:
line += str(text)
root.clipboard_append(line) # append new value to clipbaord
root = Tk()
app = App(root)
root.mainloop()
However, I am unable to bind it to a TreeView object it seems; when I run the code, I get:
Exception in Tkinter callback
<class '__main__.App'>
Traceback (most recent call last):
File "C:\Users\user1\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/user1/main_merged.py", line 56, in <lambda>
lambda t=self.partitionsOpenDiskTree: self.copyTextToClipboard(self,t))
File "C:/Users/user1/main_merged.py", line 70, in copyTextToClipboard
textList = tree.item(tree.focus())["values"]
AttributeError: 'App' object has no attribute 'item'
If I try to print out tree type, I get that it's a not a TreeView object. Any ideas on how I can get a TreeView object, so that I can figure out which item was selected?
Thanks!
-FF
So, apparently, taking out the self call seemed to work:
from tkinter.ttk import Treeview
from tkinter import *
class App:
def __init__(self, master):
self.master = master
frame = Frame(master)
master.geometry("{}x{}".format(master.winfo_screenwidth() - 100, master.winfo_screenheight() - 100))
master.resizable(False, False)
self.leftFrame = Frame(master, bg="#DADADA", width=375, relief=SUNKEN)
self.leftFrame.pack_propagate(0)
self.leftFrame.pack(side=LEFT, fill=Y, padx=1)
# This table (TreeView) will display the partitions in the tab
self.partitionsOpenDiskTree = Treeview(self.leftFrame, columns=("#"), show="headings", selectmode="browse", height=23)
yscrollB = Scrollbar(self.leftFrame)
yscrollB.pack(side=RIGHT, fill=Y)
self.partitionsOpenDiskTree.column("#", width=50)
self.partitionsOpenDiskTree.heading("#", text="#")
self.partitionsOpenDiskTree.configure(yscrollcommand=yscrollB.set)
# Bind left click on text widget to copy_text_to_clipboard() function
self.partitionsOpenDiskTree.bind("<ButtonRelease-1>", lambda event, t=self.partitionsOpenDiskTree: self.copyTextToClipboard(t))
# Adding the entries to the TreeView
for i in range(3):
self.partitionsOpenDiskTree.insert("", "end", i, values=(i), tags=str(i))
self.partitionsOpenDiskTree.pack(anchor=NW, fill=Y)
#todo: figure out where this is getting called and put in tree
def copyTextToClipboard(self, tree, event=None):
print(type(tree))
# print(type(tree.partitionsOpenDiskTree))
# triggered off left button click on text_field
root.clipboard_clear() # clear clipboard contents
textList = tree.item(tree.focus())["values"]
line = ""
for text in textList:
if line != "":
line += ", " + str(text)
else:
line += str(text)
root.clipboard_append(line) # append new value to clipbaord
print(line)
root = Tk()
app = App(root)
root.mainloop()
Output:
0
When you use bind, the callback function must have an event as its first argument, custom arguments should be put after. But as your callback does not need the event parameters, you may mask it with your lambda. So you have to change both the binding and the def of your callback:
self.partitionsOpenDiskTree.bind("<ButtonRelease-1>", lambda event, t=self.partitionsOpenDiskTree: self.copyTextToClipboard(t))
...
def copyTextToClipboard(self, tree):
should solve the problem
I'm working on developing a GUI for a project and once I put all of this into a class, it is returning saying
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "c:\users\ryan\documents\visual studio 2015\Projects\Group_3_Project\Group_3_Project\Group_3_Project.py", line 30, in <lambda>
b1 = Button(root, text = 'Submit', command = (lambda e = ents: getInfo(e)))
NameError: global name 'getInfo' is not defined
Here is my code so far:
from tkinter import*
class GUI:
fields = 'Last Name', 'First Name', 'Field', 'Phone Number', 'Office number'
def getInfo(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
def makeForm(root, fields):
entries = []
for field in fields:
row = Frame(root)
lab = Label(row, width = 15, text = field, anchor = 'w')
ent = Entry(row)
row.pack(side = TOP, fill = X, padx = 5, pady = 5)
lab.pack(side = LEFT)
ent.pack(side = RIGHT, expand = YES, fill = X)
entries.append((field, ent))
return entries
if __name__ == '__main__':
root = Tk()
root.wm_title("HoursWizard")
ents = makeForm(root, fields)
root.bind('<Return>', (lambda event, e = ents: getInfo(e)))
b1 = Button(root, text = 'Submit', command = (lambda e = ents: getInfo(e)))
b2 = Button(root, text = 'Quit', command = root.quit)
b1.pack(side = LEFT, padx = 5, pady = 5)
b2.pack(side = LEFT, padx = 5, pady = 5)
root.mainloop()
I have no idea what is going on and why it isn't working correctly. I'm sure it is an easy fix and I'm just missing something. Any help is appreciated. Thanks!
You should check the official Python tutorial and look at the section on classes. Basically, your scoping and namespaces are not what you think they are. Every class method (unless it's been designated as static) is first passed the instance itself, usually denoted with self. You would then refer to instance attributes with self.myattribute. In getInfo, for example, what you call entries isn't entries at all, but rather the instance of the GUI class that has been created.
I highly recommend you look up some tutorials for how to make an OO Tkinter app. It generally goes like this:
class App:
def __init__(self, parent):
self.parent = parent
self.parent.after(5000, self.other_method) # just a demo
# create buttons, lay out geometry, etc.
def other_method(self):
self.do_print()
def do_print(self):
print('hello world')
root = Tk()
app = App(root)
root.mainloop()