I'm wondering why my radiobutton variable is not returning a value. Kindly see my setup below :
Global declarations of the frame, radiobuttons, template variable and 'Download' button. I placed my radiobuttons in a frame. I commented the set() function here.
root = tk.Tk()
frm_radioButtons = tk.Frame(root)
template = tk.StringVar()
# template.set("m")
rbtn_create_delete = tk.Radiobutton(frm_radioButtons, text="Create/Delete items", font=(
'Arial', 8), variable="template", value="cd")
rbtn_move = tk.Radiobutton(
frm_radioButtons, text="Move items", font=('Arial', 8), variable="template", value="m")
btn_download = tk.Button(frm_radioButtons, text="Download",
font=('Arial', 7), command=generate_template, padx=15)
And created them inside a function below. Tried using global keyword but still not working. This is the main point of entry of this script.
def load_gui():
root.geometry("300x360")
frm_radioButtons.columnconfigure(0, weight=1)
frm_radioButtons.columnconfigure(1, weight=1)
#global rbtn_create_delete
#global rbtn_move
rbtn_move.grid(row=0, column=0)
rbtn_create_delete.grid(row=0, column=1)
btn_download.grid(row=1, column=0)
frm_radioButtons.pack(padx=10, anchor='w')
And here is the generate_template function when the 'Download' button is clicked. Note though, that the "Move items" radiobutton is pre-selected when I run the program even if I set(None).
It doesn't print anything.
def generate_template():
type = template.get()
print(type)
Tried a pretty straightforward code below and still did not work. It returns empty string. Switched to IntVar() with 1 & 2 as values, but only returns 0.
import tkinter as tk
def download():
print(btnVar.get())
root = tk.Tk()
btnVar = tk.StringVar()
rbtn1 = tk.Radiobutton(root, text="Button1", variable="bntVar", value="b1")
rbtn2 = tk.Radiobutton(root, text="Button1", variable="bntVar", value="b2")
rbtn1.pack()
rbtn2.pack()
btn_dl = tk.Button(root, text="Download", command=download)
btn_dl.pack()
root.mainloop()
Been reading here for the same issues but I haven't got the correct solution. Appreciate any help. tnx in advance..
Expected result: get() function return
The value passed to the variable option needs to be a tkinter variable. You're passing it a string.
In the bottom example it needs to be like this:
rbtn1 = tk.Radiobutton(root, text="Button1", variable=btnVar, value="b1")
rbtn2 = tk.Radiobutton(root, text="Button1", variable=btnVar, value="b2")
# ^^^^^^
Related
If i have this ENTRY label1 on pos1, how can i update and show "in real time" the text i write on other label 2 in position2?
label1 = Entry(root, font=('aria label', 15), fg='black')
label1.insert(0, 'enter your text here')
label1_window = my_canvas.create_window(10, 40, window=entry)
label2 = how to update and show in real time what user write on label1
If the entry and label use the same StringVar For the textvariable option, the label will automatically show whatever is in the entry. This will happen no matter whether the entry is typed in, or you programmatically modify the entry.
import tkinter as tk
root = tk.Tk()
var = tk.StringVar()
canvas = tk.Canvas(root, width=400, height=200, background="bisque")
entry = tk.Entry(root, textvariable=var)
label = tk.Label(root, textvariable=var)
canvas.pack(side="top", fill="both", expand=True)
label.pack(side="bottom", fill="x")
canvas.create_window(10, 40, window=entry, anchor="w")
root.mainloop()
Issues in your attempt: The variable names are not clear as you are creating an Entry component and then assigning it to a variable named label1 which can be confusing.
Hints: You can do one of the following to tie the label to the entry so that changing the text in the entry causes the text in the label to change:
Use a shared variable
Implement a suitable callback function. You can, for example, update the label each time the KeyRelease event occurs.
Solution 1 - Shared variable: Below is a sample solution using a shared variable:
import tkinter as tk
from tkinter import *
root = tk.Tk()
root.title('Example')
root.geometry("300x200+10+10")
user_var = StringVar(value='Enter text here')
user_entry = Entry(root, textvariable=user_var, font=('aria label', 15), fg='black')
user_entry.pack()
echo_label = Label(root, textvariable=user_var)
echo_label.pack()
root.mainloop()
Solution 2 - Callback function: Below is a sample solution using a suitable callback function. This is useful if you wish to do something more:
import tkinter as tk
from tkinter import *
root = tk.Tk()
root.title('Example')
root.geometry("300x200+10+10")
def user_entry_changed(e):
echo_label.config({'text': user_entry.get()})
user_entry = Entry(root, font=('aria label', 15), fg='black')
user_entry.insert(0, 'Enter your text here')
user_entry.bind("<KeyRelease>", user_entry_changed)
user_entry.pack()
echo_label = Label(root, text='<Will echo here>')
echo_label.pack()
root.mainloop()
Output: Here is the resulting output after entering 'abc' in the entry field:
Im having difficulties with deleting content by a function when the entry was made by another function.
def recipe_add():
recepty_add_window = Toplevel()
recepty_add_window.geometry("400x400")
name_entry_label=Label(recepty_add_window, text="Name:").grid(row=1,column=0)
name_entry = Entry(recepty_add_window, width = 50, textvariable=name_var).grid(row=1, column=1,padx=5)
b_add = Button(recepty_add_window, text="Add recipe", width=50, command=add_recipe).grid(row=6, columnspan=2, pady=5, padx = 5)
The add_recipe has name_entry.delete function inside.
def add_recipe():
name_entry.delete(0,END)
I receive: NameError: name 'name_entry' is not defined.
I tried to make name_entry global or changing the Toplevel to "single window app" by forgeting everythin that is a grid and putting it there again, nothing seems to help. Thank you all for any help.
You need to declare a global variable where you define it, not where you use it. Also, .grid() returns None, so you first want to store the Entry in the variable and then call grid():
from tkinter import *
def recipe_add():
global name_entry
name_var = StringVar()
name_entry = Entry(recepty_add_window, width = 50, textvariable=name_var)
name_entry.grid(row=1, column=1,padx=5)
def add_recipe():
name_entry.delete(0,END)
I'm looking at using a simple, currently ugly, GUI built with Tkinter to attain two variables from the user. Namely a file path and a choice from a dropdown (OptionMenu).
The variables selected will be used later in the Python script, which is where I'm running into difficulty. Put simply, how to asign the users choices to the variables: Carrier, Path.
Please see below for sample code:
from Tkinter import *
from tkFileDialog import askopenfilename
def Choose_Path():
Tk().withdraw()
return askopenfilename()
root = Tk()
root.geometry('400x400')
root.configure(background='#A2B5CD')
C_Label = Label(root, text='Carrier Choice:', bg='#A2B5CD', fg='black',font=('Calibri', 12))
C_Label.grid(row=0,sticky=W, padx =10)
I_Label = Label(root, text='Invoice Path:', bg='#A2B5CD', fg='black',font=('Calibri', 12))
I_Label.grid(row=1, sticky=W, padx =10)
var = StringVar(root)
var.set('Choose Carrier...')
option = OptionMenu(root, var, 'DHL','DPD','DX','Fedex','Geodis','Hermes','WN Direct')
option.config(relief=RAISED, highlightbackground='#A2B5CD')
option.grid(row=0,column=1, sticky=W, pady = 10)
browser = Button(root, text = 'Browse Invoice...', command=Choose_Path)
browser.grid(row=1, column=1, sticky=W, pady=10)
Button(root, text='Accept and Close').grid(column=1, sticky=S)
root.mainloop()
Any feedback would be appreciated. Thanks in advance.
Through a combination of your feedback and a little more playing around with an extra function, I now seem to be getting the results that I need. See below for what it looks like now.
from Tkinter import *
from tkFileDialog import askopenfilename
path = []
def Choose_Path():
Tk().withdraw()
path.append(askopenfilename())
def CloseGUI():
root.quit()
root.destroy()
root = Tk()
root.geometry('400x400')
root.configure(background='#A2B5CD')
C_Label = Label(root, text='Carrier Choice:', bg='#A2B5CD', fg='black',font=('Calibri', 12))
C_Label.grid(row=0,sticky=W, padx =10)
I_Label = Label(root, text='Invoice Path:', bg='#A2B5CD', fg='black',font=('Calibri', 12))
I_Label.grid(row=1, sticky=W, padx =10)
var = StringVar(root)
var.set('Choose Carrier...')
option = OptionMenu(root, var, 'DHL','DPD','DX','Fedex','Geodis','Hermes','WN Direct')
option.config(relief=RAISED, highlightbackground='#A2B5CD')
option.grid(row=0,column=1, sticky=W, pady = 10)
browser = Button(root, text = 'Browse Invoice...', command=Choose_Path)
browser.grid(row=1, column=1, sticky=W, pady=10)
b1 = Button(root, text='Accept and Close', command = CloseGUI).grid(column=1, sticky=S)
mainloop()
print var.get()
print path
Thanks for your help! +1
Two issues:
-You're going to have to figure out when to end your root's mainloop. From the moment you call root.mainloop(), currently the program will not advcance to the next line (which you don't have, but I assume you will in your final program) until you close the Tk window.
-After the mainloop has ended, you need to have your variable values somewhere. Currently, the option object (which is an OptionMenu instance) will contain the value if your carrier, so you can just do something like option.get().
The filename is slightly more complicated, because you don't store that somewhere: you return it from Choose_Path() but the return value isn't stored anywhere. Probably you're going to have to store this value in a global. (This storing has to happen within Choose_Path, e.g. FileName = askopenfilename() instead of return askopenfilename()).
I'm trying to use an Entry field to get manual input, and then work with that data.
All sources I've found claim I should use the get() function, but I haven't found a simple working mini example yet, and I can't get it to work.
I hope someone can tel me what I'm doing wrong. Here's a mini file:
from tkinter import *
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
content = entry.get()
print(content) # does not work
mainloop()
This gives me an Entry field I can type in, but I can't do anything with the data once it's typed in.
I suspect my code doesn't work because initially, entry is empty. But then how do I access input data once it has been typed in?
It looks like you may be confused as to when commands are run. In your example, you are calling the get method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop.
Try adding a button that calls the get method. This is much easier if you write your application as a class. For example:
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = tk.Entry(self)
self.button = tk.Button(self, text="Get", command=self.on_button)
self.button.pack()
self.entry.pack()
def on_button(self):
print(self.entry.get())
app = SampleApp()
app.mainloop()
Run the program, type into the entry widget, then click on the button.
You could also use a StringVar variable, even if it's not strictly necessary:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
For more information, see this page on effbot.org.
A simple example without classes:
from tkinter import *
master = Tk()
# Create this method before you create the entry
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
*
master = Tk()
entryb1 = StringVar
Label(master, text="Input: ").grid(row=0, sticky=W)
Entry(master, textvariable=entryb1).grid(row=1, column=1)
b1 = Button(master, text="continue", command=print_content)
b1.grid(row=2, column=1)
def print_content():
global entryb1
content = entryb1.get()
print(content)
master.mainloop()
What you did wrong was not put it inside a Define function then you hadn't used the .get function with the textvariable you had set.
you need to put a textvariable in it, so you can use set() and get() method :
var=StringVar()
x= Entry (root,textvariable=var)
Most of the answers I found only showed how to do it with tkinter as tk. This was a problem for me as my program was 300 lines long with tons of other labels and buttons, and I would have had to change a lot of it.
Here's a way to do it without importing tkinter as tk or using StringVars. I modified the original mini program by:
making it a class
adding a button and an extra method.
This program opens up a tkinter window with an entry box and an "Enter" button. Clicking the Enter button prints whatever is in the entry box.
from tkinter import *
class mini():
def __init__(self):
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
Button(master, text='Enter', command=self.get_content).grid(row=1)
self.entry = Entry(master)
self.entry.grid(row=0, column=1)
master.mainloop()
def get_content(self):
content = self.entry.get()
print(content)
m = mini()
I'm trying to use an Entry field to get manual input, and then work with that data.
All sources I've found claim I should use the get() function, but I haven't found a simple working mini example yet, and I can't get it to work.
I hope someone can tel me what I'm doing wrong. Here's a mini file:
from tkinter import *
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
content = entry.get()
print(content) # does not work
mainloop()
This gives me an Entry field I can type in, but I can't do anything with the data once it's typed in.
I suspect my code doesn't work because initially, entry is empty. But then how do I access input data once it has been typed in?
It looks like you may be confused as to when commands are run. In your example, you are calling the get method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop.
Try adding a button that calls the get method. This is much easier if you write your application as a class. For example:
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = tk.Entry(self)
self.button = tk.Button(self, text="Get", command=self.on_button)
self.button.pack()
self.entry.pack()
def on_button(self):
print(self.entry.get())
app = SampleApp()
app.mainloop()
Run the program, type into the entry widget, then click on the button.
You could also use a StringVar variable, even if it's not strictly necessary:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
For more information, see this page on effbot.org.
A simple example without classes:
from tkinter import *
master = Tk()
# Create this method before you create the entry
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
*
master = Tk()
entryb1 = StringVar
Label(master, text="Input: ").grid(row=0, sticky=W)
Entry(master, textvariable=entryb1).grid(row=1, column=1)
b1 = Button(master, text="continue", command=print_content)
b1.grid(row=2, column=1)
def print_content():
global entryb1
content = entryb1.get()
print(content)
master.mainloop()
What you did wrong was not put it inside a Define function then you hadn't used the .get function with the textvariable you had set.
you need to put a textvariable in it, so you can use set() and get() method :
var=StringVar()
x= Entry (root,textvariable=var)
Most of the answers I found only showed how to do it with tkinter as tk. This was a problem for me as my program was 300 lines long with tons of other labels and buttons, and I would have had to change a lot of it.
Here's a way to do it without importing tkinter as tk or using StringVars. I modified the original mini program by:
making it a class
adding a button and an extra method.
This program opens up a tkinter window with an entry box and an "Enter" button. Clicking the Enter button prints whatever is in the entry box.
from tkinter import *
class mini():
def __init__(self):
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
Button(master, text='Enter', command=self.get_content).grid(row=1)
self.entry = Entry(master)
self.entry.grid(row=0, column=1)
master.mainloop()
def get_content(self):
content = self.entry.get()
print(content)
m = mini()