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)
Related
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")
# ^^^^^^
There's an example of my code below.
I am trying to make a GUI with tkinter, in python. I want an app that has a variable, let's say var_list, that is introduced into a function as a parameter.I run this function using a button with command=lambda: analize(var_list)
I want to be able to modify the variable by pressing buttons (buttons to add strings to the list). And I have a function for that aswell:
def button_clicked(e):
if ((e["text"]).lower()) in var_list:
var_list.pop(var_list.index((e["text"]).lower())) #this adds a string to the list
else:
var_list.append((e["text"]).lower()) #this deletes the string from the list if it was already there
The function works, I tried printing the var_list and it gets updated everytime I press a button.
The problem is that I have to create the var_list as an empty list before, and when I run the function analize(var_list), it uses the empty list instead of the updated one.
Any idea on how to update the global var everytime I add/delete something from the list?
from tkinter import *
from PIL import ImageTk
def show_frame(frame):
frame.tkraise()
def button_clicked(e):
if ((e["text"]).lower()) in var_list:
var_list.pop(var_list.index((e["text"]).lower()))
else:
var_list.append((e["text"]).lower())
def analize(x):
#does stuff with the list
window = Tk()
frame1 = Frame(window)
frame2 = Frame(window)
canvas1 = Canvas(frame1,width = 1280, height = 720)
canvas1.pack(expand=YES, fill=BOTH)
image = ImageTk.PhotoImage(file="background.png")
var_list = []
button1 = Button(canvas1, text="Analize",font=("Arial"),justify=CENTER, width=10, command=lambda: [show_frame(frame2),analize(x=var_list)])
button1.place(x=(1280/2)-42, y=400)
button2 = Button(canvas1, text="String1",font=("Arial"),justify=CENTER, width=10, command=lambda: button_clicked(button2))
button2.place(x=(1280/2)-42, y=450)
button3 = Button(canvas1, text="String2",font=("Arial"),justify=CENTER, width=10, command=lambda: button_clicked(button3))
button3.place(x=(1280/2)-42, y=500)
Thank you
you can make a global variable eg:-global var
Now you can access it within other defination to manipulate the variable like this
global var
var = 0 # if you want to set a default value to the variable before calling the
function
def change_var():
global var
var = 1
USE OF GLOBAL
using global is highly recommended and is quite necessary if you are working with functions that contain or has the need to manipulate the variable
If global is not given inside the function, the variable will live inside the function and it cannot be accessed outside the function.
Hope this answer was helpful, btw, I am not sure if this the answer you are looking for as your question is not clear, maybe give a situation where you might think it might be necessary to change or update the variable
Sorry, I did not understand you but I guess this example will help you -
import tkinter as tk
root = tk.Tk()
var_list = []
def change_val(n):
var_list.append(n)
label1.config(text=var_list)
def remove():
try:
var_list.pop()
label1.config(text=var_list)
except:
pass
label1 = tk.Label(root,text=var_list)
label1.pack()
button1 = tk.Button(root,text='1',command=lambda:change_val(1))
button1.pack()
button2 = tk.Button(root,text='2',command=lambda:change_val(2))
button2.pack()
button3 = tk.Button(root,text='3',command=lambda:change_val(3))
button3.pack()
button4 = tk.Button(root,text='Pop Element',command=remove)
button4.pack()
root.mainloop()
I want to use the input value as variable and this is my code.
from tkinter import *
from tkinter import messagebox
window = Tk()
Label(window, text='Cavity number').grid(row=0)
CavNum = StringVar()
for i in range(1,8) :
globals()['L{}_CavNum'.format(i)] = StringVar()
globals()['L{}_CavNum'.format(i)] = Entry(window, textvariable=globals()['L{}_CavNum'.format(i)])
globals()['L{}_CavNum'.format(i)].grid(row=0, column=i)
window.geometry("1200x150")
window.mainloop()
everytime I do print(L1_CavNum), it says "<tkinter.Entry object .!entry>". please tell me what is the problem
You are re-using the same name for the entry widget as you use for StringVar. You could simply change globals()['L{}_CavNum'.format(i)] = StringVar() to globals()['L{}_CavNumSV'.format(i)] = StringVar() and print(L1_CavNum) to print(L1_CavNumSV.get()). However the .get() function will execute when your code runs so you will have to have a button or another event to callback the function.
I would do it like this.
from tkinter import *
def print_vars():
for x in range(len(cavity_string_vars)):
print(cavity_string_vars[x].get())
window = Tk()
Label(window, text='Cavity number').grid(row=0)
cavity_string_vars = []
cavity_entries = []
for i in range(7):
cavity_string_vars.append(StringVar())
cavity_entries.append(Entry(window, textvariable=cavity_string_vars[i]))
cavity_entries[i].grid(row=0, column=i)
print_button = Button(window, text="Print", command=print_vars)
print_button.grid(row=1, column=0)
window.geometry("1200x150")
window.mainloop()
To me associated arrays are much easier than naming each variable even when you program it as you have. Perhaps that is needed for your case.
When I run this code is says "UserName is not defined even" though its defined in the function right below it. Do the functions have to be a certain order and if so is there a way to fix that.
from tkinter import *
def MasterLogin():
Name = UserName.get()
Email = RegisterEmail.get()
Password = RegisterPassword.get()
MasterLogin = Tk()
MasterLogin.title('Login')
MasterLogin.geometry('260x100')
LoginEmail = Entry(MasterLogin, width=30).grid(row=0, column=1)
LoginEmailText = Label(MasterLogin, text=Email).grid(row=0, column=0)
def MasterRegister():
MasterRegister = Tk()
MasterRegister.title('Register')
MasterRegister.geometry('260x100')
UserName = Entry(MasterRegister, width=30).grid(row=0, column=1)
UserNameText = Label(MasterRegister, text='Name ').grid(row=0, column=0)
RegisterEmail = Entry(MasterRegister, width=30).grid(row=1, column=1)
RegisterEmailText = Label(MasterRegister, text='Email ').grid(row=1, column=0)
RegisterPassword = Entry(MasterRegister, width=30).grid(row=2, column=1)
RegisterPasswordText = Label(MasterRegister, text='Password ').grid(row=2, column=0)
RegisterCont = Button(MasterRegister, text='Continue', width=25, bg='blue', fg='white',
command=MasterLogin).grid(row=3, column=1)
When looking at this code I would suggest the following. Create a class that handles windows. In this, you can easily have functions that do what you need to do, in this code it seems you are using functions as the end all be all for your code, this would be inefficient for your code and not very future proof.
Without a class you can still achieve what you want for an Entry box, the issues here with your example is that your variables are declared along a private scope making them inaccessible to the rest of the program, this can be fixed with declaring global within a certain area of your code but this can become messy and render functions almost useless for private functionality (this can lead to many errors)
Heres my simple example for an entry box with a button that gets the data in it
from tkinter import *
def ButtonPress(entry):
entry = entry
print(entry.get())
return entry.get()
F = Tk()
F.geometry("300x100")
F.config(bg="black")
myEntry = Entry()
myEntry.pack()
myButton = Button(text="Enter",command=lambda : ButtonPress(myEntry))
myButton.pack()
F.mainloop()
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()).