Python - Simple tkinter menu - python

I need help from you.
I want to code a simple menu with tkinter, but i have problem with that.
What I want to do - In my menu,there are 2 items: "first", "second". When i click on the first, program must write 'The first' and then when I click on the second, it must write second, but the first one there will be not yet.
Can anybody help me? Thx.
I mean something like this
from tkinter import *
root = Tk()
def do_something():
# this function e.g. write 'The first'
pass
def do_something_other():
# this function e.g. write 'The second' (but 'The first' there will be not yet)
main_menu = Menu(root)
root["menu"] = main_menu
submenu1 = Menu(main_menu)
submenu1.add_command(label="Item1", command=do_something)
submenu1.add_command(label="Item2", command=do_something_other)
main_menu.add_cascade(label="Program", menu=submenu1)
My goal is, that the canvas will be changing after clicking on the Item1/Item2

You can use a Tkinter Label widget to display text in your GUI. The Label widget has a method called config that you can use to access options of the widget, to include its text attribute.
Here's a simple example. You'll have to modify it to work with your menus and specific needs:
root = Tk()
def callback(): # this function will access the
label.config(text='Updated Text') # config method of label to change it
label = Label(root, text='Original text') # make the label and set default text
btn = Button(root, text='Change text', command=callback) # make the button, which executes the callback func
label.pack()
btn.pack()
mainloop()

Related

Properly assigning a function with arguments to a button in Tkinter

I have two files:
functions.py
import tkinter as tk
class funcs():
def func1(entry):
entry.delete(0, tk.END)
main.py
import tkinter as tk
import functions as f
root = tk.Tk()
entrybox = tk.Entry(master=root).grid()
button = tk.Button(master=root, command=f.funcs.func1(entrybox)).grid()
root.mainloop()
In main.py, I have assigned the command func1 with the argument entrybox to the widget button.
My intent is to have the entry argument represent an entry widget I want to manipulate.
This line of code is broken:
button = tk.Button(master=root, command=f.funcs.func1(entrybox)).grid()
The problem is that when I run the program, the function is called immediately and does not get assigned to the button.
I am looking for a way to assign a function with arguments to a button in tkinter.
You can use an anonymous function:
tk.Button(
master=root,
command=lambda: f.funcs.func1(entrybox)
)
Python recognizes the broken line of code as an immediate call, so you have to do lambda:
button = tk.Button(master=root, command=lambda: f.funcs.func1(entrybox)).grid()
and as far as I know that will get rid of the problem.

Tkinter: KeyError when assigning function to a button

So, I have rather complicated program, and I ran into an issue with it that I can't seem to solve.
Here's the problematic part of my program:
import tkinter as tk
window = tk.Tk()
variable = "enter"
vars()[variable] = tk.Entry()
vars()[variable].insert(0, "hello")
vars()[variable].pack()
def hi():
text = vars()[variable].get()
button = tk.Button(text = "Click", command = hi)
button.pack()
I need to get the content of the entry called "enter" with the press of a button. Because of how my program works, this name, "enter" must be stored in a variable, that I called "variable" here.
What happens, is that when I press the button, I get a KeyError.
What's even weirder is that when I do the following, the program actualy works:
import tkinter as tk
window = tk.Tk()
variable = "enter"
vars()[variable] = tk.Entry()
vars()[variable].insert(0, "hello")
vars()[variable].pack()
text = vars()[variable].get()
button = tk.Button(text = "Click")
button.pack()
Here getting the content of "enter" isn't done with a button, but it's done automatically as the program runs. This is not what I want, but for some reason it works.
What can I do to make the 1st code work properly?
When you execute vars locally within hi function, a new dict object is created, that is different than the dict object created globally.
You can save the reference to the variable and use the variable within your hi function.
import tkinter as tk
window = tk.Tk()
variable = "enter"
vars()[variable] = tk.Entry()
vars()[variable].insert(0, "hello")
vars()[variable].pack()
d = vars()
def hi():
text = d[variable].get()
button = tk.Button(text="Click", command=hi)
button.pack()
window.mainloop()
I need to get the content of the entry called "enter" with the press of a button. Because of how my program works, this name, "enter" must be stored in a variable,
A better solution than using vars()[variable] is to store your widgets in a dictionary. The use of vars() provides very little value at the expense of making the code harder to understand.
import tkinter as tk
window = tk.Tk()
variable = "enter"
widgets = {}
widgets[variable] = tk.Entry()
widgets[variable].insert(0, "hello")
widgets[variable].pack()
def hi():
text = widgets[variable].get()
print(text)
button = tk.Button(text = "Click", command = hi)
button.pack()

tkinter use same widget multple times

Since no one in the Spanish StakOverFlow hasn't answered me yet, I'm asking here. I'm from ARG. I am working on an mass document upload automation. The first widget I made with tkinter asks the user what type of document wants to upload to the web. Once this process is done, I want to throw another widget to ask the same question. The thing is I don't know how to write that code. I have not learned yet how to handle classes. And the code for my widget is a copy from an example of the web, and formatted to fit my specs.
from Tkinter import Tk, Label, Button
class DocumentTypeOption:
def __init__(self, master):
self.master = master
master.iconbitmap("bigpython.ico")
master.minsize(280,150)
master.geometry("280x150")
master.title("DOCUMENT TYPE")
self.label = Label(master, text="SELECT THE DOCUMENT TYPE")
self.label.pack()
self.tipo1_button = Button(master, text="Tipo1", command=self.opcion_tipo1)
self.tipo1_button.pack()
self.tipo2_button = Button(master, text="Tipo2", command=self.opcion_tipo2)
self.tipo2_button.pack()
def funciontipo1(self):
def subirtipo1():
"things to upload doc type1"
time.sleep(0.5)
root.destroy()
time.sleep(1)
subirtipo1()
"SHOULD THE WIDGET BE CALLED HERE?"
def funciontipo2(self):
def subirtipo1():
"things to upload doc type2"
time.sleep(0.5)
root.destroy()
time.sleep(1)
subirtipo2()
"SHOULD THE WIDGET BE CALLED HERE?""
root = Tk()
my_gui = OpcionTipoDeDocumento(root)
root.mainloop()
When one type of document was uploaded I need to throw the widget once more in order to ask the user if he wants to continue with the other type of document.
There are a few options. You could simply keep the Tkinter window open and ask the user if they want to load another file. You also are using sleep() inside a tkinter instance. You cannot use sleep() within Tkinter. There is another method called after() that is for setting up timed events to replace the use of sleep(). In this case I don't think you need a delay anyway.
Here is a simple example using a tkinter class and 1 function for the doc and 1 function to ask if you want to load another one.
# import tkinter as tk # for python 3.X
# from tkinter import messagebox # for python 3.X
import Tkinter as tk
import tkMessageBox as messagebox
class DocumentTypeOption(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.iconbitmap("bigpython.ico")
self.minsize(280,150)
self.geometry("280x150")
self.title("DOCUMENT TYPE")
self.label = tk.Label(self, text="SELECT THE DOCUMENT TYPE")
self.label.pack()
self.tipo1_button = tk.Button(self, text="Tipo1", command=lambda: self.do_stuff("Tipo1"))
self.tipo1_button.pack()
self.tipo2_button = tk.Button(self, text="Tipo2", command=lambda: self.do_stuff("Tipo2"))
self.tipo2_button.pack()
def do_stuff(self, doc_type):
# things to upload doc type1
# you can do this part with a single function as long as you check the doc type first.
print(doc_type) # just to verify buttons are working.
self.check_next(doc_type)
def check_next(self, doc_type):
x = messagebox.askyesno("DOCUMENT OPTION", "Would you like to load another {}?".format(doc_type))
if x != True:
self.destroy()
my_gui = DocumentTypeOption()
my_gui.mainloop()

Python: Tkinter: Multi line scrolling entry box

I would like to make a Tkinter window able to ask for a multi line entry
(so the user will add one or more lines of text)
And then when we clic on the button be able to retrieve the values entered by user for further use.
Until now I have this script:
from Tkinter import *
import ScrolledText
class EntryDemo:
def __init__(self, rootWin):
#Create a entry and button to put in the root window
self.textfield = ScrolledText(rootWin)
#Add some text:
self.textfield.delete(0,END)
self.textfield.insert(0, "Change this text!")
self.textfield.pack()
self.button = Button(rootWin, text="Click Me!", command=self.clicked)
self.button.pack()
def clicked(self):
print("Button was clicked!")
eText = self.textfield.get()
print("The Entry has the following text in it:", eText)
#Create the main root window, instantiate the object, and run the main loop
rootWin = Tk()
#app = EntryDemo( rootWin )
rootWin.mainloop()
But it didn't seem to work, A window appear with nothing inside.
Could you help me?
#########EDIT
New code:
from Tkinter import *
import ScrolledText
class EntryDemo:
def __init__(self, rootWin):
self.textfield = ScrolledText.ScrolledText(rootWin)
#Add some text:
#self.textfield.delete(0,END)
self.textfield.insert(INSERT, "Change this text!")
self.textfield.pack()
self.button = Button(rootWin, text="Click Me!", command=self.clicked)
self.button.pack()
def clicked(self):
eText = self.textfield.get(1.0, END)
print(eText)
rootWin = Tk()
app = EntryDemo( rootWin )
rootWin.mainloop()
Sorry if it look like done with no effort by some down voters (even if I spent more than a day on it) but the Multi line text entry is not exactly what we can call well documented to learn by ourself.
Your first problem is that you commented out the app = EntryDemo( rootWin ) call, so you're not actually doing anything but creating a Tk() root window, then starting its main loop.
If you fix that, your next problem is that you're trying to use the ScrolledText module as if it were a class. You need the ScrolledText.ScrolledText class.
If you fix that, your next problem is that you're trying to delete from an empty text field, which is going to raise some kind of Tcl index error, and then you're also trying to insert at position 0 in an empty text field, which will raise the same error. There's no reason to do the delete at all, and for the insert you probably want to use INSERT as the position.
You still have multiple problems after that, but fixing these three will get your edit box up and displayed so you can start debugging everything else.
A working example based on your code. Note the comment above that both the file you import and the class within the file are named "ScrolledText"
from Tkinter import *
import ScrolledText
class EntryDemo:
def __init__(self, rootWin):
#Create a entry and button to put in the root window
self.textfield = ScrolledText.ScrolledText(rootWin)
self.textfield.pack()
#Add some text:
self.textfield.delete('1.0', END)
self.textfield.insert('insert', "Change this text!")
self.button = Button(rootWin, text="Click Me!",
command=self.clicked)
self.button.pack()
def clicked(self):
print("Button was clicked!")
eText = self.textfield.get('1.0', END)
print("The Entry has the following text in it:", eText)
self.textfield.delete('1.0', END)
rootWin = Tk()
app = EntryDemo( rootWin )
rootWin.mainloop()

Why does Tkinter hang when I call tkSimpleDialog.askstring from a lambda?

I'm developing a GUI application that models an essay. Among other things, the user can create a new topic and then populate that topic with notes. At the moment, I have two ways of creating new topics: through a dropdown option in the menu (the menu command) and through a button on the main screen (the button command). The button starts life with the text "New Topic". When the user presses the button, the program makes a new topic, asks the user to name the topic using tkSimpleDialog.askstring, and then sets the button's text to be the name of the topic and the number of notes in that topic. The button's command then changes to be adding a note to that topic.
While developing the program, I first verified that the menu command worked. It calls askstring successfully, creating a new popup window that handles input in the way I wanted. However, as soon as I added the button command, the call to askstring failed, even when called via the menu command. The window that should have the askstring dialog is whited out and the program hangs. If I comment out the button command, it works again. If I comment out the menu command, it hangs.
Here's the code where I add the command to the menu:
TopicBtn.menu.add_command(label="New Topic", underline=0,
command=self.newTopic)
Here's the code for newTopic():
def newTopic(self, button=None):
""" Create a new topic. If a Button object is passed, associate that Button
with the new topic. Otherwise, create a new Button for the topic. """
topicPrompt = "What would you like to call your new topic?"
topicName = tkSimpleDialog.askstring("New Topic", topicPrompt)
if topicName in self.topics.keys():
print "Error: topic already exists"
else:
newTopic = {}
newTopic["name"] = topicName
newTopic["notes"] = []
newTopic["button"] = self.newTopicButton(newTopic, button)
self.topics[topicName] = newTopic
self.addToTopicLists(newTopic)
Here's the code for newTopicButton():
def newTopicButton(self, topic, button=None):
""" If a Button object is passed, change its text to display the topic name.
Otherwise, create and grid a new Button with the topic name. """
if button is None:
button = Button(self.topicFrame)
index = len(self.topics)
button.grid(row=index/self.TOPICS_PER_ROW, column=(index %
self.TOPICS_PER_ROW), sticky=NSEW, padx=10, pady=10)
else:
button.unbind("<Button-1>")
buttonText = "%s\n0 notes" % topic["name"]
button.config(text=buttonText)
button.config(command=(lambda s=self, t=topic: s.addNoteToTopic(t)))
return button
And, finally, here's the code for the button command:
for col in range(self.TOPICS_PER_ROW):
button = Button(self.topicFrame, text="New Topic")
button.bind("<Button-1>", (lambda e, s=self: s.newTopic(e.widget)))
button.grid(row=0, column=col, sticky=NSEW, padx=10, pady=10)
Anybody have any idea why binding the lambda expression to the button makes askstring hang?
Edit: Thanks for the comments. Here's a minimal example that exhibits the behavior:
from Tkinter import *
import tkSimpleDialog
class Min():
def __init__(self, master=None):
root = master
frame = Frame(root)
frame.pack()
button = Button(frame, text="askstring")
button.bind("<Button-1>", (lambda e, s=self: s.newLabel()))
button.grid()
def newLabel(self):
label = tkSimpleDialog.askstring("New Label", "What should the label be?")
print label
root = Tk()
m = Min(root)
root.mainloop()
Note that switching from button.bind("<Button-1>", (lambda e, s=self: s.newLabel())) to button = Button(frame, text="askstring", command=(lambda s=self: s.newLabel())) fixes the bug (but doesn't give me a reference to the button that was pressed). I think the problem has something to do with capturing the event as one of the inputs to the lambda.
The problem you encountered here is due to the call to wait_window in the dialog you are using (you never call it yourself, but the code that implement the dialog does). For instance, the following code replicates the problem after (likely) two button clicks:
import Tkinter
def test(event=None):
tl = Tkinter.Toplevel()
tl.wait_window(tl)
root = Tkinter.Tk()
btn = Tkinter.Button(text=u'hi')
btn.bind('<Button-1>', test)
btn.pack(padx=10, pady=10)
root.mainloop()
This call to wait_window effectively does what the update command does, and is a typical example of why calling update is a bad thing to do. It enters in conflict with the <Button-1> event being handled, and hangs. The problem is that you will have to live with wait_window being used, since it belongs to the dialog's code. Apparently, if you bind to <ButtonRelease-1> then this conflict never happens. You could also use the command parameter in the button, which works fine too.
Lastly, I suggest the following to create the buttons in a cleaner manner based on what you want to achieve:
for i in range(X):
btn = Tkinter.Button(text=u'%d' % i)
btn['command'] = lambda button=btn: some_callback(button)
I figured out a workaround. From the minimum-example testing, it appears that the problem comes from making a separate call to bind and thereby accepting the event as an input to the lambda. If anyone can explain why that might be happening, I'll accept their answer over mine, but I'll accept this one for now.
The workaround is not to use a separate bind function but to create an array of buttons and then pass the correct entry in the array as the parameter to the lambda function (you can't pass the button itself, since it's being created in the line that has the lambda function).
Here's the code:
from Tkinter import *
import tkSimpleDialog
class Min():
def __init__(self, master=None):
root = master
frame = Frame(root)
frame.pack()
buttons = [None] * 2
for i in range (2):
buttons[i] = Button(frame, text="askstring",
command=(lambda s=self, var=i: s.newLabel(buttons[var])))
buttons[i].grid()
def newLabel(self, button):
label = tkSimpleDialog.askstring("New Label", "What should the label be?")
button.config(text=label)
print label
root = Tk()
m = Min(root)
root.mainloop()

Categories