Im using 2 files here. Say the variable is in the 1st file and Im using it on the 2nd. It has the initialized value of it but when I change its value the 2nd file does not recognize it. How can I update the variable so that the 2nd file reads its current value?
first module:
var = 0
def plus():
global var
var += 1
print(var)
second module(used tkinter for example)
from tkinter import *
from kk import *
root = Tk()
root.geometry("400x400+15+15")
btn = Button(root, text = "1", command = plus)
btn.pack()
def pr():
print(var)
btn1 = Button(root, text = "2", command = pr)
btn1.pack()
root.mainloop()
Following up from my comment, when you do from kk import var (or import *) you are effectively copying the variable value from the other module.
You need to copy a reference to the same object (instead of its value), you can achieve this using an object wrapper.
Try this:
class VarWrapper:
def __init__(self, initial_value):
self._value = initial_value
def __repr__(self):
return repr(self._value)
var = VarWrapper(0)
def plus():
global var
var._value += 1
print(var)
you need to import the first file function and execute it.
suppose first file name is first.py then import in second file.
from first import *
then it will work.
now you have access to first file. and to update variable use plus function.
it doesnt seem like you called plus(), if you call it it might work
#revision
perhaps if you do this?
def update ():
varInternal = var
def plusInternal ():
plus()
update()
I tried just importing again the wanted variable inside pr like so
def pr():
from kk import var
print(var)
It works, however I want to know if this way is appropriate to conventions
Related
i need help for below codes, I trying to create a software using tkinter and i have a issue on passing the value from inside function inside sub function to main module. how to get the return result use in main module and insert in mylist.
Here's the codes:
main module: test.py
from button_screener import screener
button created to open screen. command = screener
mylist = [ ]
mylist.insert(END, result)`
sub module: button_screener
def screener():
code.... (create tkinter layout code)
OK_button created to execute function execute() - command = execute
def execute():
code... after several calculation..get result below
result = list [a,b,c]
return result
Needs help and let me know if needed further clarifications.
Thank you
When you call a new function, you can think of it as creating a stack (of operations).
The function that is called latest will be at the top of the stack, and once it finishes executing it will return back to the calling function (and also return any value if you have specified in the return statement).
which means : when you do return result in your execute() function, it will provide that result to it's calling function : screener()
since you are calling screener() from your main module, you should capture the output of execute() in screener(), and then return that to the screener() 's calling function - which is main.
def screener():
code.... (create tkinter layout code)
#OK_button created to execute function execute() - command = execute
def execute():
code... after several calculation..get result below
result = list [a,b,c]
return result
result_from_execute = execute() #capturing response from execute()
return result_from_execute #return the result to the main module
Since those functions are executed by a button click, whatever returned from those functions will be discarded.
As the result you want to return is a list, you can pass the required list variable to screener() as an argument which will be updated inside the function.
Below is a simple example:
import tkinter as tk
def screener(result):
def execute():
# do some calculation
a, b, c = 1, 2, 3
# then update result
result[:] = [a, b, c]
win.destroy()
win = tk.Toplevel()
tk.Button(win, text='OK', command=execute).pack(padx=50, pady=50)
win.grab_set()
mylist = []
root = tk.Tk()
tk.Button(root, text='Sceener', command=lambda:screener(mylist)).pack()
tk.Button(root, text='Show', command=lambda:print(mylist)).pack()
root.mainloop()
I'm working on a project and i would like to get the Value of an Entry created in a def (turned on by a button on Tkinter)
So I have my main tkinter menu, with a button which will call the def "panier".
The def "panier" is creating the Entry "value" and another button to call a second def "calcul".
The second def "calcul" will do things with the value of Entry...
But then, in the def "calcul", when i'm trying to do value.get() it tells "NameError: name 'value' is not defined"
Here is the code, btw the Entry must be created by the def...
from tkinter import *
def panier():
value=Entry(test)
value.pack()
t2=Button(test,text="Validate",command=calcul)
t2.pack()
def calcul(value):
a=value.get()
#here will be the different calculations I'll do
test=Tk()
t1=Button(test,text="Button",command=panier)
t1.pack()
test.mainloop()
Appreciate every feedback :)
You can make the variable global like this:
from tkinter import *
def panier():
global value
value = Entry(test)
value.pack()
t2 = Button(test, text="Validate", command=calcul)
t2.pack()
def calcul():
a = value.get()
print(a)
#here will be the different calculations I'll do
test = Tk()
t1 = Button(test, text="Button", command=panier)
t1.pack()
test.mainloop()
The global value line makes the variable global so you can use it anywhere in your program.
You can also pass in the variable as an argument like what #JacksonPro suggested
t2 = Button(test, text="Validate", command=lambda: calcul(value))
This is one way to do it. Globally create a collection (list or dictionary) to hold a reference to the Entry. When you create the Entry, add it to the collection. I made it with either a list or dictionary for holding the references, so toggle the commented variations in all three places to try it both ways.
import tkinter as tk
def panier():
for item in ('value', ):
ent = tk.Entry(test)
collection.append(ent)
# collection[item] = ent
ent.pack()
t2 = tk.Button(test,text="Validate",command=calcul)
t2.pack()
def calcul():
a = collection[0].get()
# a = collection['value'].get()
print(a)
collection = []
# collection = {}
test = tk.Tk()
t1 = tk.Button(test, text="Button", command=panier)
t1.pack()
test.mainloop()
I'm working hard to solve this problem, can someone help me ?
There is what I mean by 'set' an argument:
from tkinter import *
window = Tk()
I=1
def add():
global I
menu1.add_command(label=I, command=lambda:Text(I))
I=I+1
def Text(I):
print(I)
menubar = Menu(window)
menu1 = Menu(menubar, tearoff=0)
menu1.add_command(label="Add", command=add)
menu1.add_separator()
menu1.add_command(label="Quit", command=window.quit)
menubar.add_cascade(label="Files", menu=menu1)
window.config(menu=menubar)
window.mainloop()
I want when we click on add and after on '1' it print '1', and when we add '2' and click on it, it print '2' but it always print the value of I, how can I set the argument by
menu1.add_command(label=I, command=lambda:Text(1))
for exemple ?
I don't know if I'm clear but I don't know how explain it !
Change your Text function to be a closure:
def Text(I):
def inner():
print(I)
return inner
Then change your add function to be this:
def add():
global I
text = Text(I)
menu1.add_command(label=I, command=text)
I=I+1
This will save the I in the text variable. The text variable is actually a function, inner, that will print I when called.
Or you could make your closure inline if you wanted to use the Text function somewhere else:
import functools
...
menu1.add_command(label=I, command=functools.partial(Text, i))
I think your problem is the lambda:Text(I). In this case, you have created a closure, but the closure knows I to be a global and is evaluating it at a later date.
You probably want to immediately evaluate Text(I) and use that as your result:
texti = Text(I) # Immediate evaluation
menu1.add_command(label=I, command=lambda:texti) # Return prior value of "I"
This comes from a button that when pressed generates a radiobutton. I am not able to access to the choice made with radiobutton. Everything works fine, but the output of selected function is zero. I try using both local and global var but the result is the same.
def callback_st(): # RadioButton select technology
var = IntVar()
m=0
for m in range(len(un_tech)):
Radiobutton(radio_frame, text=un_tech[m], value=m, variable=var,
command=selected(var)).pack(anchor=W)
def selected(var):
print(var)
This doesn't work. I solved using lambda:
def selected(jst):
global sel_technology
sel_technology=un_tech[jst]
print(sel_technology)
def callback_st(): #RadioButton select technology
var_st = IntVar()
m=0
for m in range(len(un_tech)):
Radiobutton(radio_frame, text=un_tech[m], value=m, variable=var_st,
command = lambda jst=m: selected(jst)).pack(anchor=W)
This works as i want, but it isn't the solution that i want and i think is not the correct way. So, somebody can help me to find the right way?
In your first try, you call selected immediately, when var has a value of 0. You avoided this with the lambda expression, but you are correct that this is an awkward workaround for the original mistake. Make var global and have selected access it as a global. Modifying your first code:
var = IntVar()
def selected():
print(var.get())
def callback_st():
...
...command=selected...
If you were defining a class and methods, var would be an instance attribute instead of global.
The idea of this code is, the user presses the first button and enters what they want, then they press the second button and it prints it out. Can someone please tell me why my return statement is not working? It says that 'variable' is not defined. Thanks in advance for taking the time to read my question.
from tkinter import*
def fun():
variable = input('Enter Here:')
return variable
def fun_2():
print(variable)
window = Tk()
button = Button(text = 'Button', command = fun )
button2 = Button(text = 'Button2', command = fun_2 )
button.pack()
button2.pack()
window.mainloop()
In python when you create a variable inside of a function, it is only defined within that function. Therefore other functions will not be able to see it.
In this case, you will probably want some shared state within an object. Something like:
class MyClass:
def fun(self):
self.variable = input('Enter Here:')
def fun_2(self):
print(self.variable)
mc = MyClass()
window = Tk()
button = Button(text = 'Button', command = mc.fun )
button2 = Button(text = 'Button2', command = mc.fun_2 )
button.pack()
button2.pack()
fun() may return a value, but Tkinter buttons don't do anything with that return value.
Note that I used the phrase return a value, not return a variable. The return statement passes back the value of an expression, not the variable variable here. As such, the variable variable is not made into a global that other functions then can access.
Here, you can make variable a global, and tell fun to set that global:
variable = 'No value set just yet'
def fun():
global variable
variable = input('Enter Here:')
Since you did use any assignment in fun2, variable there is already looked up as a global, and it'll now successfully print the value of variable since it now can find that name.
The problem is in in fun2(). It does not get variable as an input parameter.
def fun_2(variable):
print(variable)
But note that you have to call fun_2 now with the appropriate argument. Also, as the function stands right now, there is little point in having the function if you just do a print inside of it.
Take away message: variable is not global in Python, and as such you must pass it to each function that wants to use it.