【发布时间】:2018-06-24 20:27:24
【问题描述】:
我确实尽了最大努力自己找到了解决方案,但没有。我想从滑块中获取值,然后单击按钮将其保存到 csv 文件(工作正常)。唉,在我的按钮事件期间,我无法获得 tkinter.Scale 的值。我想知道它是否全局变量可以解决我的问题,但我还没有让它们工作。我特别惊讶,因为我可以在更改比例时打印比例值的实时流,但无法以有用的方式保存它。如果您能回答我的任何困惑,或者让我知道我的问题是否不清楚,或者无论如何可能会更好,我将不胜感激。以下是一些帮助我走到这一步的链接:
https://www.programiz.com/python-programming/global-local-nonlocal-variables
Tkinter - Get the name and value of scale/slider
这是我将最终值打印 10 次的尝试:
from tkinter import *
root = Tk()
def scaleevent(v): #Live update of value printed to shell
print(v)
variable = v
def savevalue():
global variable #This is what I want to work, but doesn't
for i in range(10):
print(variable)
scale = Scale(orient='vertical', command=scaleevent).grid(column=0,row=0)
button = Button(text="button", command=savevalue).grid(column=1, row=0)
root.mainloop()
这是我尝试使用.get() 解决我的问题:
from tkinter import *
root = Tk()
def savevalue(): #print value 10 times. In final version I will save it instead
for i in range(10):
print(scale.get()) #I really want this to work, but it doesn't,
root.destroy #is it because .get is in a function?
scale = Scale(orient='vertical', command=scaleevent).grid(column=0,row=0)
button = Button(text="button", command=savevalue).grid(column=1, row=0)
root.mainloop()
(Python 3.5,Windows 10)
编辑:
这是我第一次尝试使用全局变量时遇到的错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Me\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "C:\Users\Me\Documents\programing\tkinter scale question.py", line 15, in savevalue
print(variable)
NameError: name 'variable' is not defined
这就是我运行第一个代码示例时发生的情况,同样是我的实际项目。谢谢布莱恩·奥克利!
【问题讨论】:
-
运行代码时会发生什么?你有错误吗?请发布错误。
-
有更好的方法来完成这项任务,但您的第一个代码示例的一个简单解决方法是将
global variable指令从savevalue移动到scaleevent。 -
在您的第一个 sn-p 中,您需要将
global variable声明移动到scaleevent()函数,否则它只是那里的一个局部变量——因此在调用savevalue()时它从未定义过该函数所做的只是尝试读取变量的当前值。 -
成功了!!比你 PM 2Ring 和 martineau,我很高兴它就这么简单。我很想知道还有什么其他方法可以做到这一点,但我很高兴这很有效。谢谢。
-
感谢 Marineau,看起来确实更好。