如何通过按tkinter来获得刻度值?

时间:2018-06-24 20:27:25

标签: python tkinter get slider

我确实竭尽所能自行找到解决方案,但没有。我想从滑块获取值,然后单击按钮将其保存到csv文件(工作正常)。 las,在按钮事件期间,我无法获取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

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

2 个答案:

答案 0 :(得分:0)

您必须在global中使用scaleevent,因为您尝试将值分配给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()

答案 1 :(得分:-1)

从tkinter导入*

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