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.
Related
i found a tutorial on google which integer value could be update by using .config(). So I had using the below code to update the value. I think my logic it wrong by put the while loop like that , but i not sure how could i update the a = a + 1 on to the gui.
My code :
import tkinter as tk
from random import randint
master_window = tk.Tk()
master_window.geometry("250x150")
master_window.title("IntVar Example")
lab = tk.Label(master_window)
integer_variable = tk.IntVar()
integer_variable.set(2)
label = tk.Label(master_window,text="output", height=50)
label.place(x=80, y=80)
a = 25
def update():
my_data=integer_variable.get(a) # read the value of selected radio button
label.config(text=str(my_data)) # Update the Label with data
while True:
a = a + 1
master_window.update()
master_window.mainloop()
The setup you have so far is quite strange and your intuition that the logic is wrong is accurate.
Here's an alternative to get you started - note how I refrain from using external variables and instead use the .set() and get() operations to change the value of the integer_variable:
import tkinter as tk
master_window = tk.Tk()
master_window.geometry("250x150")
master_window.title("IntVar Example")
integer_variable = tk.IntVar()
integer_variable.set(2)
label = tk.Label(master_window, text=integer_variable.get())
label.grid(row=0, column=0)
button = tk.Button(master_window, text="Update value", command=update)
button.grid(row=1, column=0)
def update():
curr_integer_variable_value = integer_variable.get()
updated_integer_value = curr_integer_variable_value + 1
integer_variable.set(updated_integer_value)
label.config(text=str(integer_variable.get()))
master_window.mainloop()
Im trying to detect a button press in tkinker but every method on google does not work for me, i want to change variable value for my python project.
Here's the basic code:
from tkinter import *
win= Tk()
win.geometry("500x600")
up = Button(win, text="⬆", bg="yellow", borderless=1, width=150, height=100, command = var = 1)
up.place(x=0, y = 500)
win.mainloop()
How do i do that?
Sourced from: To Detect Button Press In Python Tkinter Module
You could just place the variable change within a function
up = Button(win, text="⬆", bg="yellow", borderless=1, width=150, height=100, command=changeVar())
def changeVar():
var = 1
Or something close to this, assuming it's in the global namespace, since you're attemping to change it via var = 1 anyway.
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()
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 trying to use Tkinter's Entry widget. I can't get it to do something very basic: return the entered value. Does anyone have any idea why such a simple script would not return anything? I've tried tons of combinations and looked at different ideas.
This script runs but does not print the entry:
from Tkinter import *
root = Tk()
E1 = Entry(root)
E1.pack()
entry = E1.get()
root.mainloop()
print "Entered text:", entry
Seems so simple.
Edit
In case anyone else comes across this problem and doesn't understand, here is what ended up working for me. I added a button to the entry window. The button's command closes the window and does the get() function:
from Tkinter import *
def close_window():
global entry
entry = E.get()
root.destroy()
root = Tk()
E = tk.Entry(root)
E.pack(anchor = CENTER)
B = Button(root, text = "OK", command = close_window)
B.pack(anchor = S)
root.mainloop()
And that returned the desired value.
Your first problem is that the call to get in entry = E1.get() happens even before your program starts, so clearly entry will point to some empty string.
Your eventual second problem is that the text would anyhow be printed only after the mainloop finishes, i.e. you close the tkinter application.
If you want to print the contents of your Entry widget while your program is running, you need to schedule a callback. For example, you can listen to the pressing of the <Return> key as follows
import Tkinter as tk
def on_change(e):
print e.widget.get()
root = tk.Tk()
e = tk.Entry(root)
e.pack()
# Calling on_change when you press the return key
e.bind("<Return>", on_change)
root.mainloop()
from tkinter import *
import tkinter as tk
root =tk.Tk()
mystring =tk.StringVar(root)
def getvalue():
print(mystring.get())
e1 = Entry(root,textvariable = mystring,width=100,fg="blue",bd=3,selectbackground='violet').pack()
button1 = tk.Button(root,
text='Submit',
fg='White',
bg= 'dark green',height = 1, width = 10,command=getvalue).pack()
root.mainloop()