在tkinter中,可以通过以下几种方式在两个函数之间传递变量:
global
关键字声明该变量,然后就可以在函数之间共享这个变量。例如:import tkinter as tk
def function1():
global my_variable
my_variable = "Hello"
def function2():
print(my_variable)
root = tk.Tk()
button1 = tk.Button(root, text="Function 1", command=function1)
button1.pack()
button2 = tk.Button(root, text="Function 2", command=function2)
button2.pack()
root.mainloop()
import tkinter as tk
class MyApplication:
def __init__(self):
self.my_variable = ""
def function1(self):
self.my_variable = "Hello"
def function2(self):
print(self.my_variable)
app = MyApplication()
root = tk.Tk()
button1 = tk.Button(root, text="Function 1", command=app.function1)
button1.pack()
button2 = tk.Button(root, text="Function 2", command=app.function2)
button2.pack()
root.mainloop()
import tkinter as tk
def function1(variable):
variable.set("Hello")
def function2(variable):
print(variable.get())
root = tk.Tk()
my_variable = tk.StringVar()
button1 = tk.Button(root, text="Function 1", command=lambda: function1(my_variable))
button1.pack()
button2 = tk.Button(root, text="Function 2", command=lambda: function2(my_variable))
button2.pack()
root.mainloop()
以上是在tkinter中两个函数之间传递变量的几种常见方法。根据具体的需求和场景,选择适合的方法来实现变量的传递。
领取专属 10元无门槛券
手把手带您无忧上云