在Tkinter中显示Canvas中的比例值

时间:2015-06-19 12:39:48

标签: python user-interface tkinter slider tkinter-canvas

我正在尝试在Tkinter中开发GUI。我有一个主要代码

from menus import *
from Tkinter import *
from SpeedControl import *

Main = Tk()
Main.tk_setPalette(background='white')
GenerateMenus(Main)
GenerateSlider(Main)
mainloop()

GenerateSlider的代码是     来自Tkinter import *

def GenerateSlider(master):
    display1 = Canvas(master, width=150, height=80, relief=RAISED, bd=5)
    display1.grid(row=0,column=0)
    display1.create_rectangle(10, 10, 150, 80, fill='dark red')
    slider1 = Scale(master, from_=0, to=100, length=400,
                    tickinterval=10, orient=HORIZONTAL, relief=SUNKEN, bd=5,
                    bg='white', troughcolor='black', sliderrelief=RAISED)
    slider1.grid(row=0,column=1)
    display1.create_text(50,20, font='Helvatica 28', text=slider1.get(), fill='white', anchor=NW)
    display2 = Canvas(master, width=150, height=80, relief=RAISED, bd=5)
    display2.grid(row=1,column=0)
    display2.create_rectangle(10, 10, 150, 80, fill='dark red')
    slider2 = Scale(master, from_=0, to=100, length=400,
                    tickinterval=10, orient=HORIZONTAL, relief=SUNKEN, bd=5,
                    bg='white', troughcolor='black', sliderrelief=RAISED)
    slider2.grid(row=1,column=1)
    display2.create_text(50,20, font='Helvatica 24', text=slider2.get(), fill='white', anchor=NW)

我在这里要做的是程序应该在画布内显示滑块的当前值作为文本。初始值显示在画布中,但我需要一种方法来在滑块移动时更新值。

1 个答案:

答案 0 :(得分:1)

让我详细说明一下我的评论。这就是我的意思(使用类和一个简化的例子来满足我的目的):

from Tkinter import *

class Window():

    def __init__(self, master):

        self.display1 = Canvas(master, width=150, height=80, relief=RAISED, bd=5)
        self.display1.grid(row=0,column=0)
        self.display1.create_rectangle(10, 10, 150, 80, fill='dark red')

        self.slider1 = Scale(master, from_=0, to=100, length=400,
                tickinterval=10, orient=HORIZONTAL, relief=SUNKEN, bd=5,
                bg='white', troughcolor='black', sliderrelief=RAISED, command = self.updateCanvas)
        self.slider1.grid(row=0,column=1)

        self.createdText = self.display1.create_text(50, 20, font = 'Helvatica 28', text = self.slider1.get(), fill = 'white', anchor = NW)

    def updateCanvas(self, sliderVal):

        self.display1.itemconfig(self.createdText, text = sliderVal)

master = Tk()
w = Window(master)
master.mainloop()

编辑:从调用updateCanvas中移除lambda作为command,因为Scale小部件在调用时会传递它的值。我能够给updateCanvas一个自动传递的参数sliderVal,然后我用它来更新文本。同时删除了对update()的调用,因为这是不必要的。

编辑2 :更新了代码以反映fhdrsdg的建议,该建议允许更新文本而无需销毁&每次调用更新函数时重新创建它。