Get variable value created inside a function - python

I want to get a variable from a function to use this variable in another function.
Simple example:
from tkinter import *
def test():
intro = "I am "
name = "Phil"
text = intro + name
def printresult():
print(text)
root = Tk()
root.title("Test")
testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)
testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)
mainloop()
If I press the testbutton and afterwards the printbutton, then I get the error "name 'text' is not defined".
So how am I able to get the text variable from the def test() to use it in the def printresult()?

You need to save the value somewhere well known:
from tkinter import *
def test():
intro = "I am "
name = "Phil"
text = intro + name
test.text = text # save the variable on the function itself
def printresult():
print(test.text)
root = Tk()
root.title("Test")
testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)
testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)
mainloop()

Since you are using tkinter, I'd use a StringVar to store the result. Using a string var makes it easy for other tkinter widgets to use the value.
from tkinter import *
def test():
intro = "I am "
name = "Phil"
text.set(intro + name)
def printresult():
print(text.get())
root = Tk()
root.title("Test")
text = StringVar()
testbutton = Button(root, text="Test", command = test)
printbutton = Button(root, text="print Test", command = printresult)
testbutton.grid(row = 1, column = 0)
printbutton.grid(row = 1, column = 1)
mainloop()

Related

I'm unable to get a string out of tkinter entrybox

import random
import tkinter as tk
frame = tk.Tk()
frame.title("koeweils baldadige encyptor")
frame.geometry('400x200')
printButton = tk.Button(frame,text = "Print", command = lambda: zandkasteel())
printButton.pack()
freek = tk.Text(frame,height = 5, width = 20)
freek.pack()
input_a = freek.get(1.0, "end-1c")
print(input_a)
fruit = 0
fad = input_a[fruit:fruit+1]
print(fad)
schepje = len(input_a.strip("\n"))
print(schepje)
def zandkasteel():
lbl.config(text = "Ingevulde string: "+input_a)
with open("luchtballon.txt", "w") as chocoladeletter:
for i in range(schepje):
n = random.randint()
print(n)
leuk_woord = ord(fad)*n
print(leuk_woord)
chocoladeletter.write(str(leuk_woord))
chocoladeletter.write(str(n))
chocoladeletter.write('\n')
lbl = tk.Label(frame, text = "")
lbl.pack()
frame.mainloop()
I need to get the string that was entered into the text entry field freek. I have tried to assign that string to input_a, but the string doesn't show up.
Right now, input_a doesn't get anything assigned to it and seems to stay blank. I had the same function working before implementing a GUI, so the problem shouldn't lie with the def zandkasteel.
To be honest I really don't know what to try at this point, if you happen to have any insights, please do share and help out this newbie programmer in need.
Here are some simple modifications to your code that shows how to get the string in the Text widget when it's needed — specifically when the zandkasteel() function gets called in response to the user clicking on the Print button.
import random
import tkinter as tk
frame = tk.Tk()
frame.title("koeweils baldadige encyptor")
frame.geometry('400x200')
printButton = tk.Button(frame, text="Print", command=lambda: zandkasteel())
printButton.pack()
freek = tk.Text(frame, height=5, width=20)
freek.pack()
def zandkasteel():
input_a = freek.get(1.0, "end-1c")
print(f'{input_a=}')
fruit = 0
fad = input_a[fruit:fruit+1]
print(f'{fad=}')
schepje = len(input_a.strip("\n"))
print(f'{schepje=}')
lbl.config(text="Ingevulde string: " + input_a)
with open("luchtballon.txt", "w") as chocoladeletter:
for i in range(schepje):
n = random.randint(1, 3)
print(n)
leuk_woord = ord(fad)*n
print(leuk_woord)
chocoladeletter.write(str(leuk_woord))
chocoladeletter.write(str(n))
chocoladeletter.write('\n')
lbl = tk.Label(frame, text="")
lbl.pack()
frame.mainloop()

How To Save a key to a dictionary forever?

iam trying to make a phonebook using python and tkinter . I need to add new numbers to my phonebook
by adding elements to the dictionary but i can't access the numbers again after the programme is closed .
from tkinter import*
#defining the submit button
def submit():
global my_dict
new = entry2.get()
new2 = entry3.get()
my_dict.update({new:new2})
#definig the add button
def add():
top = Toplevel(root)
top.configure(background="black")
top.geometry("400x400")
top.title("Add new member")
label6 =Label(top,text="Welcome",bg="black",fg="orange")
label6.place(x=135,y=13)
global entry2
entry2 = Entry(top,width=23)
entry2.place(x=102,y=78)
label7 = Label(top,text="Name",bg="black",fg="orange")
label7.place(x=48,y=78)
global entry3
entry3 = Entry(top,width = 23)
entry3.place(x=108,y=127)
label8 = Label(top,text="phone number",bg ="black",fg="orange")
label8.place(x=0,y=129)
button3 = Button(top,text="Submit",command = submit)
button3.place(x=185,y=200)
button5 = Button(top,text = "close",command = top.quit)
button5.place(x=185,y=300)
#defining the chek button
def check():
person = entry.get()
if person in my_dict:
phone = my_dict.get(person)
print("Found: " + person + " : " + phone)
# Erase the old result by placing a blank label
label0 = Label(root, width=200, bg ="black", fg = "black").place(x=10,y=167)
label5 = Label(root, text = person + " : " + phone, bg ="black", fg = "orange").place(x=10,y=167)
#creating the main window
root = Tk()
global my_dict
my_dict = {"john":'7598769587'}
root.title("vole phone book")
root.geometry("400x400")
root.configure(background="black")
label = Label(root,text="phone book",bg="black",fg="orange",width=13).place(x=133,y=23)
label2 = Label(root,text="Enter here.",bg = "black",fg="orange").place(x=2,y=89)
entry = Entry(root,width = 27)
entry.place(x=89,y=90)
button =Button(root,text="Check",bg="yellow",fg="red",command=check).place(x=190,y=129)
button2=Button(root,text="Add",width=23,command = add).place(x=120,y=300)
root.mainloop()
this is my code,what to do?
Variables in Python are not saved to disk, they only exist in memory (RAM) unless you explicitly save it there yourself.
You can either save to a file directly or, use a database instead.
See Here for using Pickle to do what you want.

Changing text of labels defined in a loop

I'm trying to make a scalable counter.
In the first window you enter how many counters you want.
In the second window there are labels and buttons used to add one to the label.
Here is my code:
from tkinter import *
root = Tk()
def newWindow():
window = Toplevel()
for i in range(int(textbox.get())):
exec("global label"+ str(i))
exec("label" + str(i) + " = Label(window, text = '0')")
exec("label" + str(i) + ".grid(row = 0, column = i)")
exec("global button"+ str(i))
exec("button" + str(i) + " = Button(window, text = 'Add', command = lambda: setText(label" + str(i) + "))")
exec("button" + str(i) + ".grid(row = 1, column = i)")
def setText(label):
label.config(text = str(int(label.cget("text")) + 1))
textbox = Entry(root)
textbox.grid(row = 0)
submitButton = Button(root, text = "Submit", command = newWindow)
submitButton.grid(row = 0, column = 1)
root.mainloop()
However this is the error I get:
name 'label_' is not defined
where _ is i.
Making them global didn't fix this either.
Help please!
If you're using exec in this way, you're doing something very wrong.
The simple solution is to add widgets to a list or dictionary. Though, in this specific case you don't need that because you're never referencing the label anywhere but in the button command.
Here's a working example:
from tkinter import *
root = Tk()
def newWindow():
global labels
window = Toplevel()
labels = {}
for i in range(int(textbox.get())):
label = Label(window, text='0')
button = Button(window, text='Add', command = lambda l=label: setText(l))
label.grid(row=0, column=i)
button.grid(row=1, column=i)
# this allows you to access any label later with something
# like labels[3].configure(...)
labels[i] = label
def setText(label):
label.config(text = str(int(label.cget("text")) + 1))
textbox = Entry(root)
textbox.grid(row = 0)
submitButton = Button(root, text = "Submit", command = newWindow)
submitButton.grid(row = 0, column = 1)
root.mainloop()
If you wanted to make use of labels, you could have your button pass in the index, and let setText get the widget from the dictionary:
def setText(i):
label = labels[i]
label.configure(...)
...
button = Button(..., command=lambda i=i: setText(i))

Python display variable with tkinter inside a method

The program I just wrote is my playground for finding out how Tkinter works.
My question is how do I display my variable "timelabel" as a Label.
I allready made a label called timerefresher yet it doesnt show up.
I am aware that the DigitalClock class isn't written efficiently. I am new to this ;).
def Clockupdate(time):
timelabel = time
timerefresher = Label(root, textvariable=timelabel)
timerefresher.pack()
#print(timelabel) To test if variable made it this far.
class DigitalClock:
def secondrefesher(self):
newtime = ""
while 1 == 1:
oldtime = datetime.datetime.now()
a = str(oldtime.hour)
b = str(oldtime.minute)
c = str(oldtime.second)
curtime = (a+":"+b+':'+c)
if curtime != newtime:
newtime = curtime
#print("made it here")
Clockupdate(newtime)
else:
time.sleep(0.20)
DC = DigitalClock()
root = Tk()
mainlabel = Label(root, text="Hey this is working!")
Pressme = Button(root, text="Press me!", command=Presstoshowtextandpic,
bg='red', fg='white')
Clock = Button(root, text="Clock?", command=DC.secondrefesher, bg='blue',
fg='white')
Photo = PhotoImage(file="test.png")
ShowPhoto = Label(root, image=Photo)
mainlabel.pack()
Pressme.pack()
Clock.pack()
root.mainloop()
Ok so Here is what I would do with your code to accomplish what you are trying to do.
First lets make sure we have the correct imports.
from tkinter import *
import datetime
import time
I created this doNothing() function as a place holder for any commands I am not currently testing.
def doNothing():
pass
Now the way you had your Clockupdate(time): function would cause the label to be added every time you click the clock button. so this is probably not what you want as it just keeps adding new labels instead of replacing the existing one. Take a look at this function. All I do in this is .config() the text to be the time argument from the function. Note you do not need to redefine the time to timelabel or anything of the sort, just use time as your varable.
def Clockupdate(time):
timerefresher.config(text = time)
I don't know if you wanted to use a class for a specific reason but I think you should just use a function here. Also try to keep your quotes consistent. I know they are interchangeable but its good practice to keep them consistent.
def secondrefesher():
newtime = ""
oldtime = datetime.datetime.now()
a = str(oldtime.hour)
b = str(oldtime.minute)
c = str(oldtime.second)
curtime = (a + ":" + b + ":" + c)
if curtime != newtime:
newtime = curtime
Clockupdate(newtime)
Note I always place commands at the end of any config of a button. It helps when managing code so you can just check the end of each line as you scroll through your code. I also changed the command for Pressme to doNothing so I could test the code. You didn't provide the code for Presstoshowtextandpic and would not be able to test the code with out that part. Remember when asking a question here to use MCVE.
root = Tk()
mainlabel = Label(root, text="Hey this is working!")
Pressme = Button(root, text = "Press me!", bg = "red", fg = "white", command = doNothing)
Clock = Button(root, text = "Clock?", bg = "blue", fg = "white", command = secondrefesher)
Photo = PhotoImage(file = "test.png")
ShowPhoto = Label(root, image = Photo)
Here I created the time label just once and then you can call the update function all you want to change the text to current time.
timerefresher = Label(root, text = "")
timerefresher.pack()
mainlabel.pack()
Pressme.pack()
Clock.pack()
root.mainloop()
Here is what I think the completed code should look like for you.
from tkinter import *
import datetime
import time
def Clockupdate(time):
timerefresher.config(text = time)
def secondrefesher():
newtime = ""
oldtime = datetime.datetime.now()
a = str(oldtime.hour)
b = str(oldtime.minute)
c = str(oldtime.second)
curtime = (a + ":" + b + ":" + c)
if curtime != newtime:
newtime = curtime
Clockupdate(newtime)
root = Tk()
mainlabel = Label(root, text = "Hey this is working!")
Pressme = Button(root, text = "Press me!", bg = "red", fg = "white", command = Presstoshowtextandpic)
Clock = Button(root, text = "Clock?", bg = "blue", fg = "white", command = secondrefesher)
Photo = PhotoImage(file = "test.png")
ShowPhoto = Label(root, image = Photo)
timerefresher = Label(root, text = "")
timerefresher.pack()
mainlabel.pack()
Pressme.pack()
Clock.pack()
root.mainloop()
Edit:
In case you are trying to create a clock that is always active and does not require you to click the button you can use .after().
Take a look at this example.
from tkinter import *
import datetime
import time
root = Tk()
mainlabel = Label(root, text = "Hey this is working!")
Photo = PhotoImage(file = "test.png")
timerefresher = Label(root, text = "")
timerefresher.pack()
status_time = ""
def tick():
global status_time
time2 = time.strftime("%H:%M:%S")
if time2 != status_time:
status_time = time2
timerefresher.config(text = time2)
timerefresher.after(200, tick)
tick()
mainlabel.pack()
root.mainloop()
You should have written an MCVE so that one can test your code, especially that things are missing (such as Presstoshowtextandpic()).
When reading the rest of your code, I think you need to read about variable classes and modify Clockupdate() as follows:
def Clockupdate(time):
timelabel = StringVar() # modified
timelabel.set(time) # added
timerefresher = Label(root, textvariable=timelabel.get()) #modified
timerefresher.pack()
P.S. You should write clock_update() instead of Clockupdate()

Tkinter Radiobuttons autoselect and always on...Python 2.7

I am trying to create a GUI for one of my school projects and I have an issue with the radio buttons... When I run the script the radio buttons automatically activate and the stay on.
from Tkinter import *
def sel():
label.config(text = "You have selected 'HOSTS'")
target = "hosts"
def selnet():
label.config(text = "You have selected 'NETWORKS'")
target = "networks"
root = Tk()
var = StringVar()
var2 = IntVar()
R1 = Radiobutton(root, text = "HOSTS", var = 'hosts', value = 1, command = sel)
R1.pack(anchor = W)
R2 = Radiobutton(root, text = "NETWORKS", var = 'networks', value = 2, command = selnet)
R2.pack(anchor = W)
label = Label(root)
label.pack()
root.mainloop()
Add an option 'variable' to link two radiobuttons. E.g. (look at the end of RadioButton constructors):
R1 = Radiobutton(root, text = "HOSTS", var = 'hosts', value = 1, command = sel, variable=var2)
R1.pack(anchor = W)
R2 = Radiobutton(root, text = "NETWORKS", var = 'networks', value = 2, command = selnet, variable=var2)
R2.pack(anchor = W)

Categories