I'm trying to update the content of a label, in Python, by clicking a button. For each clicks a counter will be raised and the value of the label will be updated by the current value of the counter (j). Here is the code:
import time
import random
import MySQLdb
from Tkinter import *
j=0
def PrintNumber():
global j
j+=1
print j
return
mgui=Tk()
mgui.geometry('200x200')
mgui.title('Queue System')
st = Button(mgui, text="Next Customer", command = PrintNumber)
st.pack()
f = PrintNumber()
label = Label(mgui, text=f)
label.pack()
mgui.mainloop()
Please be kind, i'm new in Python. :)
You can use a Tkinter variable class instance to hold a value. If you assign the textvariable option of the Label widget to the variable class instance, it will update automatically as the value of the instance changes. Here's an example:
from Tkinter import *
root = Tk()
var = IntVar() # instantiate the IntVar variable class
var.set(0) # set it to 0 as the initial value
# the button command is a lambda expression that calls the set method on the var,
# with the var value (var.get) increased by 1 as the argument
Button(root, text="Next Customer", command=lambda: var.set(var.get() + 1)).pack()
# the label's textvariable is set to the variable class instance
Label(root, textvariable=var).pack()
mainloop()
You can change the label text in the function that responds to the command (PrintNumber() in this case) using label.config(), e.g.:
from tkinter import *
def PrintNumber():
global j,label
j+=1
label.config(text=str(j))
return
j = 0
mgui=Tk()
mgui.geometry('200x200')
mgui.title('Queue System')
st = Button(mgui, text="Next Customer", command = PrintNumber)
st.pack()
label = Label(mgui, text=str(j))
label.pack()
mgui.mainloop()
Here is another way you could do it
import time
import random
import MySQLdb
from Tkinter import *
def PrintNumber(label):
PrintNumber.counter += 1 #simulates a static variable
print PrintNumber.counter
label.configure(text=str(PrintNumber.counter)) #you update label here
mgui=Tk()
mgui.geometry('200x200')
mgui.title('Queue System')
PrintNumber.counter = 0 #add an attribute to a function and use it as a static variable
label = Label(mgui) #create label
#pass the label as parameter to your function using lambda notation
st = Button(mgui, text="Next Customer", command=lambda label=label:PrintNumber(label))
st.pack()
label.pack()
mgui.mainloop()
Related
I am new in python
I wanted to make a program that when you write a specific string in entry it compares it with a string and get an output but it doesnt go well ,where is the mistake i have done?
from tkinter import *
from tkinter.ttk import *
app=Tk()
load = Entry(app, width=10)
loadvar = StringVar
z = loadvar.get()
if z == "winner"
Label(app,text="congrats",).grid(row=1,column=0)
app.mainloop()
from tkinter import *
from tkinter.ttk import *
app = Tk()
# Entry
loadvar = StringVar()
load = Entry(app, width=10, textvariable=loadvar)
load.grid(row=0, column=0)
load.focus()
def compare():
if loadvar.get() == "winner":
# Label
Label(app, text="congrats", ).grid(row=1, column=0)
# Button
Button(text="Compare", command=compare).grid(row=0, column=1)
app.mainloop()
In your code, you have not placed the Entry widget yet. Moreover, you should use Buttons and link them with the function you want so that you can carry it out each time you are using it. Otherwise, you are check if the text inside entry is equal to 'winner' even before typing into it.
loadvar = StringVar
This line must be before creating Entry and then put in "textvariable" attribute of the widget.
I made a new object of tk.IntVar and called it pwHardness
but its value is something random like 140358607937898IntVar.
i want the radio buttons to set the value of the variable pwHardness 1 or 2
import tkinter as tk
pwHardness = tk.IntVar
window = tk.Tk()
window.geometry("1600x500")
window.configure(bg="#323e52")
Label = tk.Label(text="Password Gen", background="#323e52", foreground="#fafafa")
Label.config(width=200)
Label.config(font=("Courier", 44))
setPwRadioButtonEasy = tk.Radiobutton(
text="Easy PW",
padx = 20,
var=pwHardness,
variable=pwHardness,
value=1,
)
setPwRadioButtonHard = tk.Radiobutton(
text="Hard PW",
padx = 20,
var=pwHardness,
variable=pwHardness,
value=2,
)
label1 = tk.Label(text=pwHardness)
Label.pack()
setPwRadioButtonEasy.pack()
setPwRadioButtonHard.pack()
label1.pack()
window.mainloop()
FYI This is going to be a Password Generator.
You aren't initializing the variable, you're just taking the IntVar object.
pwHardness = tk.IntVar()
would initialize a new IntVar – you're missing the parentheses.
Additionally, you're passing the var as a "string" value to text.
You'd want
label1 = tk.Label(text=pwHardness.get())
to "read" the variable into the label. However, it won't refresh automatically with that configuration.
You are missing parentheses after pwHardness = tk.IntVar. It should be pwHardness = tk.IntVar(). Additionally, change label1 = tk.Label(text=pwHardness) to label1 = tk.Label(textvar=pwHardness), so the label gets automatically updated. And, tk.IntVar must be initiated with a parent, e.g. the toplevel window. Example :
import tkinter as tk
root = tk.Tk()
var = tk.IntVar(root)
label = tk.Label(root, textvar=var)
label.pack()
while True:
inp = input("enter new value ")
if inp != "quit":
var.set(int(inp))
else:
break
why is this listbox not returning my selection? I added the returnSelected() function with a button thinking that it needed to be triggered. My goal is to create as simple a possible function that a user can select a reduced list, and I am clearly not understanding the tkinter flow.
import tkinter
def listboxinput3():
# <ListboxSelect> callback function and current selection
def cb(event):
label['text'] = str(event) + '\n' + str(lb.curselection())
def returnSelected():
myselection = [my_list[k] for k in lb.curselection()]
print(myselection )
root = tkinter.Tk()
root.title('Parameter Selection')
root.geometry('200x600')
my_list = dir(tkinter)
var = tkinter.StringVar(value=my_list)
label = tkinter.Label(root)
label.grid()
btnGet = tkinter.Button(root,text="Get Selection",command=returnSelected)
btnGet.grid()
lb = tkinter.Listbox(root, listvariable=var, selectmode='extended')
lb.grid()
lb.bind('<<ListboxSelect>>', cb)
#tkinter.Button(root, text="Show Selected", command=returnSelected).pack()
selected_text_list = [lb.get(i) for i in lb.curselection()]
root.mainloop()
return selected_text_list
selected_text_list = listboxinput3()
Thanks
It seems you don't know how GUI works. You create selected_text_list before mainloop() which starts program, displays window, gets your click, runs cb and returnSelected, etc. - so you create this list before you even see window and select item.
You have to create it inside function cb or returnSelected which is executed after you select item. And it will need global selected_text_list to assing it to external variable because button can't get it and assing it to external variable.
import tkinter
def listboxinput3():
# <ListboxSelect> callback function and current selection
def cb(event):
label['text'] = str(event) + '\n' + str(lb.curselection())
def returnSelected():
global selected_text_list
selected_text_list = [my_list[k] for k in lb.curselection()]
root = tkinter.Tk()
root.title('Parameter Selection')
root.geometry('200x600')
my_list = dir(tkinter)
var = tkinter.StringVar(value=my_list)
label = tkinter.Label(root)
label.grid()
btnGet = tkinter.Button(root, text="Get Selection", command=returnSelected)
btnGet.grid()
lb = tkinter.Listbox(root, listvariable=var, selectmode='extended')
lb.grid()
lb.bind('<<ListboxSelect>>', cb)
#tkinter.Button(root, text="Show Selected", command=returnSelected).pack()
# selected_text_list = [lb.get(i) for i in lb.curselection()] # useless - it is executed before you even see window
# display window, run function assigned to button when you click, etc.
root.mainloop()
return selected_text_list
selected_text_list = listboxinput3()
print(selected_text_list)
I'm trying to see what checkbox are checked and write a if/else function to do stuff. The number of check boxes depends on the number of topics I parse into the program and create a checkbox for each item.
I added:
chk_state = IntVar()
But this is only good if you are using one checkbox.
I am using a list to generate all my checkboxes:
Which generates these variables for each checkbox:
'chk0', 'chk1', 'chk2', 'chk3', 'chk4', 'chk5', 'chk6', 'chk7', 'chk8', 'chk9', 'chk10', 'chk11', 'chk12', 'chk13', 'chk14', 'chk15', 'chk16', 'chk17', 'chk18', 'chk19', 'chk20', 'chk21', 'chk22', 'chk23', 'chk24']
from tkinter import *
from tkinter import messagebox
from reader import openit
import sys
data = openit(sys.argv[1])
window = Tk()
#set size of window
window.geometry('850x400')
window.title("Chose Your ROS Topic" )
lbl = Label(window, text="Topics", font=("Arial Bold", 25))
lbl.grid(column=0,row=0)
#check checkbox value boolean
chk_state = IntVar()
#chk_state.set(0) #uncheck
#chk_state.set(1) #checked
#Looping through list and adding each one as a checked button
counter = 0
selected_list = []
for x in data.split(","):
# global selected_list
#print(x)
#print(counter)
name = "chk" + str(counter)
# appends each checkbox name to a list
selected_list.append(name)
name = Checkbutton(window, text='%s' % x , font=(15), onvalue=1, offvalue=0, variable=chk_state)
if counter == 0:
name.grid(column=1, row=1)
#print('only for counter 0')
else:
name.grid(column=1, row=1+counter -1)
#print("the rest")
counter += 1
#After selecting all the topics you want to graph
def topics_selected():
#messagebox.showinfo('Topics picked', 'graphing all your checked topics')
#for topics in
if chk_state.get():
print("some checked topics")
else:
print("Nothing is checked")
# Adding input tkinter textbox
txt = Entry(window,width=10)
txt.grid(column=1,row=0)
# Function that changes buttond
def inputcheck():
res = "Topics picked " + txt.get()
lbl.configure(text = res)
def clicked():
lbl.configure(text="Parser was clicked, checking rosbag")
# Adding button widget
btn = Button(window, text="ROS topic parser", bg="orange", fg="black", command=topics_selected)
btn.grid(column=2, row=1)
#Create a checkbox
#chk = Checkbutton(window, text='Choose')
#chk.grid(column=0, row=4)
window.mainloop()
if __name__ == "__main__":
pass
#print(data)
I want to be able to add whatever was selected to a list and push that list to another function.
You need to create a tkinter variable for each Checkbutton. Right now all you Checkbutton shares the same variable chk_state.
To make this work, simply move your definition of IntVar inside the for loop:
...
selected_list = {} #use a dict to store name/IntVar pair; can use a list also
for num, x in enumerate(data.split(",")): #use enumerate to get a num count
chk_state = IntVar() #create a new IntVar in each iteration
selected_list[num] = chk_state #save name/IntVar pair
name = Checkbutton(window, text='%s' % x , font=(15), onvalue=1, offvalue=0, variable=chk_state)
if num == 0:
name.grid(column=1, row=1)
else:
name.grid(column=1, row=1+num-1)
#After selecting all the topics you want to graph
def topics_selected():
if any(s.get() for s in selected_list.values()): #check if any checkbutton is checked
print ("some checked topics")
print ([s.get() for s in selected_list.values()])
else:
print("Nothing is checked")
You could use tk.BooleanVar for each of your check boxes, and set their values inside a for loop.
Keeping the variables in a list allows you to pass the selection to a function.
import tkinter as tk
DEFAULTS = [True, False, False, False]
def display_selected_options(options, values):
for option, value in zip(options, values):
print(f'{option}: {value.get()}')
def create_option_selectors(frame, options, option_variables) -> None:
for idx, option in enumerate(options):
option_variables[idx].set(DEFAULTS[idx])
tk.Checkbutton(frame,
variable=option_variables[idx],
onvalue=True,
offvalue=False,
text=option,
).pack(side=tk.LEFT)
root = tk.Tk()
options = ['chk0', 'chk1', 'chk2', 'chk3']
option_variables = [tk.BooleanVar(root) for _ in range(len(options))]
frame = tk.Frame(root)
create_option_selectors(frame, options, option_variables)
frame.pack()
display_options = tk.Button(root, text='validate', command=lambda options=options,
values=option_variables: display_selected_options(options, values))
display_options.pack()
root.mainloop()
Alternatively, you could use a dictionary to store the option -> value pairs:
I'm trying to get a set of buttons that will change the value of my global variable "y". I'm pretty new to python, and am very new to tkinter. I have tried using lambda and solutions in similar questions haven't seemed to fix the issue.
Here is my code:
import tkinter as tk
from tkinter import *
master=Tk()
def assignint(value):
global y
y = value
y= StringVar()
frame = Frame(master)
frame.grid(row=0, columnspan=4)
for i in range(2):
Grid.rowconfigure(master,i,weight=1)
for i in range(4):
Grid.columnconfigure(master,i,weight=1)
Button1 = Button(master,text='Fault1',command= lambda: assignint(0))
Button1.grid(row=1, column=0,sticky=N+S+E+W)
Button2 = Button(master,text='Fault2',command= lambda: assignint(1))
Button2.grid(row=1, column=1,sticky=N+S+E+W)
Button3 = Button(master,text='Fault3',command= lambda: assignint(2))
Button3.grid(row=1, column=2,sticky=N+S+E+W)
Button4= Button(master,text='Fault4',command= lambda: assignint(3))
Button4.grid(row=1, column=3,sticky=N+S+E+W)
if y.get()!='':
print('The value of y is:', y.get())
mainloop()
You need to use set method when changing a StringVar's value.
as in replace:
y = value
with:
y.set(value)