如何用按键获取刻度值?

2024-05-08 18:45:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的尽了我最大的努力自己找到解决方案,但没有。我想从一个滑块的值,然后保存到一个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()来解决我的问题:

^{pr2}$

(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

这就是我运行第一个代码示例时发生的情况,与我的实际项目类似。谢谢布莱恩·奥克利!在


Tags: ofnameinvaluetkintervariable按钮global
2条回答

来自tkinter import*

root = Tk()
variable=0 # only you forgot this 
def scaleevent(v):
    print(v)
    global variable

    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()

您必须在scaleevent中使用global,因为您试图将值赋给variable。如果没有global,它将v分配给本地{},那么它就不存在于{}

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()返回{}。
你必须分两行来完成:

^{pr2}$

代码

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()

相关问题 更多 >