Change label text on button using values from tuple click tkinter - python

I have a list of strings sorted in a tuple like this:
values = ('1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript')
My simple code is:
from tkinter import *
root = Tk()
values = ('1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript')
ru = Button(root,
text="Next",
)
ru.grid(column=0,row=0)
lab = Label(root,
text=values[0])
lab.grid(column=1,row=0)
ru2 = Button(root,
text="Previous"
)
ru2.grid(column=2,row=0)
root.mainloop()
I have two tkinter buttons "next" and "previous", the text value of the Label is directly taken from the tuple (text=value[0]), however I would want to know how to show the next string from the tuple when the next button is pressed, and how to change it to the previous values when the "previous" button is pressed. I know it can be done using for-loop but I cannot figure out how to implement that. I am new to python.

Use Button(..., command=callback) to assign function which will change text in label lab["text"] = "new text"
callback means function name without ()
You will have to use global inside function to inform function to assign current += 1 to external variable, not search local one.
import tkinter as tk
# --- functions ---
def set_next():
global current
if current < len(values)-1:
current += 1
lab["text"] = values[current]
def set_prev():
global current
if current > 0:
current -= 1
lab["text"] = values[current]
# --- main ---
values = ('1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript')
current = 0
root = tk.Tk()
ru = tk.Button(root, text="Next", command=set_next)
ru.grid(column=0, row=0)
lab = tk.Label(root, text=values[current])
lab.grid(column=1, row=0)
ru2 = tk.Button(root, text="Previous", command=set_prev)
ru2.grid(column=2, row=0)
root.mainloop()
BTW: if Next has to show first element after last one
def set_next():
global current
current = (current + 1) % len(values)
lab["text"] = values[current]
def set_prev():
global current
current = (current - 1) % len(values)
lab["text"] = values[current]

Related

Where do I make a mistake with this tkinter focus?

I made a tool to add multiple order numbers in our system. The first time a row of entry cells is placed the focus is where it should be. But the second time the focus is not in the new left cell. First I thought it has to do with using the tab key. But if I understand the code correct, I first execute the moving of the tab key and then execute the code. So the command to focus on the new left cell is last.
Where am I going wrong?
import tkinter as tk
from tkinter import ttk
# Create variables for later use
order_list = []
date_list = []
row_number = 0
active_order_entry = None
active_date_entry = None
def add_a_row_of_entry_cells():
global row_number
global active_order_entry
global active_date_entry
row_number += 1
order_entry = ttk.Entry()
order_entry.grid(row=row_number, column=0)
order_entry.focus()
date_entry = ttk.Entry()
date_entry.grid(row=row_number, column=1)
# Make these entries the active ones
active_order_entry = order_entry
active_date_entry = date_entry
# Add entries to a list
order_list.append(order_entry)
date_list.append(date_entry)
def tab_pressed(event):
if active_order_entry.get() != "" and active_date_entry.get() != "":
add_a_row_of_entry_cells()
else:
print("Order, date or both are not filled yet")
def button_pressed():
print("Button pressed")
# Create window
window = tk.Tk()
# Add function to the Tab key
window.bind("<Tab>", tab_pressed)
# Labels on top of the columns
label_order_number = tk.Label(window, text="Order", fg="#22368C")
label_order_number.grid(row=row_number, column=0)
label_date = tk.Label(window, text="Date", fg="#22368C")
label_date.grid(row=row_number, column=1)
# Create empty row
empty_row = tk.Label(window)
empty_row.grid(row=87, column=0)
# Create button
button = tk.Button(window, text="Add orders", command=lambda: button_pressed())
button.grid(row=98, column=0, columnspan=3)
# Create empty row
empty_row = tk.Label(window)
empty_row.grid(row=99, column=0)
# Add the first row
add_a_row_of_entry_cells()
window.mainloop()

tkinter 'var' for radiobutton is always returning 0

from the List of radio button I want to know which one was clicked
Whenever a radio button (In python Tkinter) is clicked its returning 0...
I tried the following method:
declaring the 'var' variable global
passing var variable in all function
But none of the steps are working
def get_date(var):
path_read = E1.get()
date_list = readunparseddata.getdate_unparseddate(path_read)
show_date(date_list,var)
def show_date(list_date,var):
print(var)
frame = Tk()
#v.set(1)
Label(frame,text="""Choose your Date :""",justify=LEFT,padx=20).pack( anchor = W )
count = 0
for date in list_date:
print count
R1=Radiobutton(frame, text=date, padx=20, value=count, variable=var, command=lambda:ShowChoice(var))
R1.pack()
count+=1
def ShowChoice(var):
print "option : " + str(var.get())
top = Tk()
var=IntVar()
The problem was with the instance of Tk() that I was creating.
Below link ( 1 ) said to use TopLevel() which solved the problem
Increment the counter in the function that is being called when the radio button is selected.
Here is an example to help you.It prints the number of times the button is selected.
import Tkinter as tk
count=0
root = tk.Tk()
def add():
global count
count=count+1
print count
v = tk.IntVar()
tk.Label(root,
text="""Choose a
programming language:""",
justify = tk.LEFT,
padx = 20).pack()
tk.Radiobutton(root,
text="Python",
padx = 20,
variable=v,
value=1,command=add).pack(anchor=tk.W)
root.mainloop()

How to get values of checkbuttons from for loop tkinter python

I am new to programming in tkinter and am very stuck on using checkbuttons. I have created multiple checkbuttons in one go, all with different text for each one and a different grid position. However I have no idea how to get the value of each button or how to even set it. I want to be able to get the state/value for each button and if it is checked, then another function is called. How do I set and call the value/state of each button? Can this be done in a for loop or do I have to create them individually?
def CheckIfValid(self, window):
Class = self.ClassChosen.get()
Unit = self.UnitChosen.get()
Topic = self.TopicChosen.get()
if Class == '' or Unit == '' or Topic == '':
tm.showinfo("Error", "Please fill in all boxes")
else:
QuestionData = OpenFile()
QuestionsList = []
for x in range (len(QuestionData)):
#if QuestionData[x][2] == Topic:
QuestionsList.append(QuestionData[x][0])
for y in range(len(QuestionsList)):
self.ButtonVal[y] = IntVar()
Checkbutton(window, text = QuestionsList[y], padx = 20, variable = self.ButtonVal[y]).grid(row = 12 + y, column = 2)
ConfirmSelection = Button(window, text = "Set Homework", command = lambda: SetHomeworkClass.ConfirmHomework(self)).grid()
print(variable.get()) #here I would like to be able to get the value of all checkbuttons but don't know how
You use the list of IntVars either called from a command= in the Checkbutton or in the Button. Don't know why you are calling another class's object, SetHomeworkClass.objectConfirmHomework(self). It doesn't look like that will work as you have it programmed, as that is another name space and the list of IntVars is in this name space, but that is another topic for another thread.
try:
import Tkinter as tk # Python2
except ImportError:
import tkinter as tk # Python3
def cb_checked():
# remove text from label
label['text'] = ''
for ctr, int_var in enumerate(cb_intvar):
if int_var.get(): ## IntVar not zero==checked
label['text'] += '%s is checked' % cb_list[ctr] + '\n'
root = tk.Tk()
cb_list = [
'apple',
'orange',
'banana',
'pear',
'apricot'
]
# list of IntVar for each button
cb_intvar = []
for this_row, text in enumerate(cb_list):
cb_intvar.append(tk.IntVar())
tk.Checkbutton(root, text=text, variable=cb_intvar[-1],
command=cb_checked).grid(row=this_row,
column=0, sticky='w')
label = tk.Label(root, width=20)
label.grid(row=20, column=0, sticky='w')
# you can preset check buttons (1=checked, 0=unchecked)
cb_intvar[3].set(1)
# show what is initially checked
cb_checked()
root.mainloop()

Tkinter: Link an Entry Widget to a Button to a Function

I am new to Tkinter and not to sure how to proceed. I am trying to link a function that I define to a entry widget that is activated by a button. but I can't figure out how to get the three to communicate to each other. I would like it to print as well as return to the script so that I can be used in another function. This is what I have so far:
import Tkinter as tk
def TestMath(x):
calculate = x + 4
print calculate
return calculate
root = tk.Tk()
entry = tk.Entry(root)
value = entry.get()
number = int(value)
button = tk.Button(root, text="Calculate")
calculation = TestMath(number)
root.mainloop()
Button calls function assigned to command= (it has to be "function name" without () and arguments - or lambda function)
TestMath assigns calculation to global variable result and other functions can have access to that value.
import Tkinter as tk
def TestMath():
global result # to return calculation
result = int(entry.get())
result += 4
print result
result = 0
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
button = tk.Button(root, text="Calculate", command=TestMath)
button.pack()
root.mainloop()
Function called by button don't have to return value because there is no object which could receive that value.

Making python/tkinter label widget update?

I'm working on getting a python/tkinter label widget to update its contents. Per an earlier thread today, I followed instructions on how to put together the widgets. At runtime, however, the label widget does NOT change contents, but simply retains its original content. As far as I can tell, decrement_widget() is never called at all. Any ideas?
def snooze (secs):
"""
Snoozes for the given number of seconds. During the snooze, a progress
dialog is launched notifying the
"""
root = Tkinter.Tk()
prompt = 'hello'
label1 = Tkinter.Label(root, text=prompt, width=len(prompt))
label1.pack()
remaining = secs
def decrement_label ():
text = "Snoozing %d sec(s)" % remaining
remaining -= 1
label1.config(text=text, width=100)
label1.update_idletasks()
for i in range(1, secs + 1):
root.after(i * 1000, decrement_label )
root.after((i+1) * 1000, lambda : root.destroy())
root.mainloop()
You'll want to set the label's textvariable with a StringVar; when the StringVar changes (by you calling myStringVar.set("text here")), then the label's text also gets updated. And yes, I agree, this is a strange way to do things.
See the Tkinter Book for a little more information on this:
You can associate a Tkinter variable with a label. When the contents of the variable changes, the label is automatically updated:
v = StringVar()
Label(master, textvariable=v).pack()
v.set("New Text!")
I think you're getting a "referenced before assignment" error because Python thinks remaining is in the local scope.
In Python 3, you can say nonlocal remaining. But in Python 2, I don't believe there's a way to refer to a non-local, non-global scope. This worked for me:
remaining = 0
def snooze (secs):
"""
Snoozes for the given number of seconds. During the snooze, a progress
dialog is launched notifying the
"""
global remaining
root = Tkinter.Tk()
prompt = 'hello'
label1 = Tkinter.Label(root, text=prompt, width=len(prompt))
label1.pack()
remaining = secs
def decrement_label ():
global remaining
text = "Snoozing %d sec(s)" % remaining
remaining -= 1
label1.config(text=text, width=100)
label1.update_idletasks()
for i in range(1, secs + 1):
root.after(i * 1000, decrement_label )
root.after((i+1) * 1000, lambda : root.destroy())
root.mainloop()
import tkinter
from tkinter import *
# just init some vars
remaining = 0
secs = 0
root = tkinter.Tk()
prompt = StringVar()
def snooze (secs):
"""
Snoozes for the given number of seconds. During the snooze, a progress
dialog is launched notifying the
"""
def decrement_label ():
global remaining, prompt
remaining -= 1
prompt.set('Snoozing %d sec(s)' % remaining)
label1.update_idletasks()
if not remaining:
print("end ... ")
root.destroy()
global remaining
prompt.set("hello")
label1 = tkinter.Label(root, textvariable=prompt, width=30)
label1.pack()
remaining = secs
for i in range(1, secs + 1):
root.after(i * 1000, decrement_label )
snooze(10)
root.mainloop()
To update text in a label you can try the following:
from tkinter import *
root = Tk()
root.title("Title")
root.geometry('300x300')
def clear_text(self):
txtE.delete(0, 'end')
def new_label(event=None):
Entree = txtE.get()
lbl1['text'] = Entree.title()
clear_text(txtE)
lbl1 = Label(root, text='Hello There')
lbl1.pack()
txtE = Entry(root)
txtE.focus()
txtE.pack()
Button(root, text='Enter', command=new_label).pack()
Button(root, text='Quit', command=root.destroy).pack(side=BOTTOM)
root.bind('<Return>', new_label)
root.mainloop()
I think you have to call snooze(secs) function
After that if your code again not works try this
Set a variable
Variable = StringVar()
In the label widget you can set "textvariable" argument to the above mentioned "Variable".
Eg:
label1 = Label(root,textvariable = Variable).pack()
And you can update by setting a new value to "Variable"
Eg:Variable.set("hi")
Hope you got it !!!

Categories