在创建 tkinter gui 时,我尝试为我的滑块创建一个通用函数,而不是为每个滑块使用一个函数。这是到目前为止的样子:
import tkinter as tk
from tkinter import ttk
import globalvars
globalvars.init()
leftFrame = tk.Tk()
def sliderChanged(value, sliderval, text, label):
globals()[value] = int(sliderval)
label.config(text=f"{text}: {globals()[value]}")
print(globals()[value])
print(globalvars.mutation_speed)
mutationslider = ttk.Scale(leftFrame, from_=0, to=1000, orient=tk.HORIZONTAL,length=200, value=100, style="custom.Horizontal.TScale")
mutationslider.grid(row=1, column=1)
mutationlabel = tk.Label(leftFrame, font=("Helvetica", 11, "bold"), bg='#0000b3', fg="white")
mutationlabel.grid(row=2, column=1)
mutationslider.configure(command=lambda val: sliderChanged(globalvars.mutation_speed, mutationslider.get(), "Mutation Speed", mutationlabel))
leftFrame.mainloop()
和 globalvars 文件:
def init():
global mutation_speed
mutation_speed = 100
我遇到的问题是,虽然标签正在更新,打印(globals()[value])语句中的打印值也是如此,但我试图更改的实际值(globalvars.mutation_speed)没有改变(它保持初始值 100)。因此,我认为问题在于 globals()[value] = int(sliderval) 行,或者可能在于函数中传递/使用特定参数的方式。