Python中main函数如何调用其他函数修改过的float变量r1x
报错根本原因
你遇到的未定义报错和global关键字本身无关,核心是两个逻辑问题:
global关键字仅用来标记「函数内操作的变量来自全局作用域」,不会自动给变量赋值。你的代码里r1x只有在random_location_no被触发执行时才会被赋值,但main函数运行到no_button.place(relx = r1x)这行时,按钮还没被点击过,random_location_no从来没执行过,全局作用域里根本没有已赋值的r1x,直接引用必然报错。- 就算你提前给
r1x设了初始值绕过初始化报错,点击按钮修改全局变量后,按钮位置也不会自动变化——place()的布局参数只在组件第一次布局时读取一次,后续普通变量改动不会同步更新组件属性。
可直接运行的修复代码
修复点包括:提前给r1x设置初始值、回调内更新完变量后主动刷新按钮布局、补全缺失的yes_press回调逻辑:
import tkinter import random # 全局作用域提前初始化r1x,给默认初始位置 r1x = round(random.uniform(0.6, 0.8), 2) no_button = None # 先占位存按钮引用,方便回调里修改位置 def random_location_no(): global r1x, no_button print('no pressed') r1x = round(random.uniform(0.6, 0.8), 2) print(r1x) # 修改变量后主动更新按钮位置 no_button.place_configure(relx=r1x, rely=0.55, anchor='c') def yes_press(): # 补全缺失的Yes按钮回调,可按需修改逻辑 print("yes pressed") def main(): global window, no_button window = tkinter.Tk() window.title ('iq test') window.geometry('800x800') txt = tkinter.Label(window, text = ' Are you stupid :3', font = ("Oswald", 45, "bold")) txt.place(relx=0.5, rely=0.22, anchor="c") no_button = tkinter.Button (window, text = 'No', fg = 'Black', height = 5, width = 10, command = random_location_no, font = ('Finlandica', 15)) # 初始化时直接用已经赋值的全局r1x no_button.place(relx = r1x, rely = 0.55, anchor = 'c') yes_button = tkinter.Button (window, text = 'Yes', fg = 'Black', height = 5, width = 10, command = yes_press, font = ('Finlandica', 15)) yes_button.place(relx = 0.3, rely = 0.55, anchor = 'c') window.mainloop() main()
其他可选实现思路
如果不想用太多全局变量,也可以用面向对象的方式写Tkinter界面,把组件引用、位置变量都作为类的属性存储,能避免全局变量过多带来的维护问题。
内容的提问来源于stack exchange,提问作者lilsolar
相关产品推荐
相关产品推荐

