我真的尽力自己找到解决方案,但还没有。我想从滑块中获取值,然后单击按钮将其保存到 csv 文件(工作正常)。唉,我无法tkinter.Scale
在我的按钮事件期间获得 的值。我想知道全局变量是否可以解决我的问题,但我还没有让它们起作用。我特别惊讶,因为我可以在更改比例值时打印实时流,但无法以有用的方式保存它。如果您能回答我的任何困惑,或者让我知道我的问题是否不清楚或无论如何可能会更好,我将不胜感激。以下是一些帮助我走到这一步的东西的链接:
https://www.programiz.com/python-programming/global-local-nonlocal-variables
这是我尝试将最终值打印 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
inscaleevent
因为您尝试为 赋值variable
。没有global
它分配v
给本地variable
然后它不存在于savevalue
from tkinter import *
root = Tk()
def scaleevent(v):
global variable
print(v)
variable = v
def savevalue():
print(variable)
Scale(orient='vertical', command=scaleevent).grid(column=0,row=0)
Button(text="button", command=savevalue).grid(column=1, row=0)
root.mainloop()
至于第二个版本,你弄错了 var = Widget(...).grid()
它分配None
给var
因为grid()/pack()/place()
返回None
。
你必须在两行中做到这一点:
var = Widget(...)
var.grid(...)
代码
from tkinter import *
root = Tk()
def savevalue():
print(scale.get())
root.destroy() # you forgot ()
scale = Scale(orient='vertical')
scale.grid(column=0,row=0)
button = Button(text="button", command=savevalue)
button.grid(column=1, row=0)
root.mainloop()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句