Reputation: 57
Here is the first cell of Jupyter Notebook which is a simple tkinter program.
Can I assign the scale value to the variable "a" and use it in the following cells of Jupyter Notebook?
Now the value of "a" I can get is always 0 in the following cells of Jupyter Notebook.
from tkinter import *
a = 0
def sel():
selection = "Value = " + str(var.get())
a = var.get()
label.config(text = selection)
root = Tk()
var = DoubleVar()
scale = Scale( root, variable = var )
scale.pack(anchor=CENTER)
button = Button(root, text="Get Scale Value", command=sel)
button.pack(anchor=CENTER)
label = Label(root)
label.pack()
root.mainloop()
#print(a)
Upvotes: 0
Views: 272
Reputation: 605
a = var.get()
: Here a
is a local variable within the function.
a = 0
def sel():
a = 2
print("a from sel:", a)
sel()
print("a:", a)
Output:
a from sel: 2
a: 0
Alternatively, you can make a
a global variable.
from tkinter import *
global scale_value
# set default
scale_value = 0
def save_scale_value(event):
global scale_value
# save the current value while the program is running
scale_value = event.widget.get()
print(f"Saved: {scale_value}")
def sel():
# reuse a variable in another function
global scale_value
print(f"global scale_value: {scale_value}")
selection = "Value = " + str(var.get())
label.config(text = selection)
root = Tk()
var = DoubleVar()
scale = Scale( root, variable = var )
scale.pack(anchor=CENTER)
button = Button(root, text="Get Scale Value", command=sel)
button.pack(anchor=CENTER)
label = Label(root)
label.pack()
scale.bind("<ButtonRelease>", save_scale_value)
root.mainloop()
# this will only print after the window is closed, when the root is destroyed
print(scale_value)
Also, you may not need an additional variable. You can use var
after closing the window too.
from tkinter import *
def sel():
selection = "Value = " + str(var.get())
label.config(text = selection)
root = Tk()
var = DoubleVar()
scale = Scale(root, variable = var)
scale.pack(anchor=CENTER)
button = Button(root, text="Get Scale Value", command=sel)
button.pack(anchor=CENTER)
label = Label(root)
label.pack()
root.mainloop()
# this will only print after the window is closed, when the root is destroyed
print(var.get())
# Later, you can assign the scale value to a variable in a cell.
# name = var.get()
Upvotes: 1