画布上的 tkinter 可变值 [英] tkinter changeable value on canvas

查看:38
本文介绍了画布上的 tkinter 可变值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在单击按钮时更改画布上的文本标签.如果单击向上"按钮,我想将标签增加 10,如果单击向下"按钮,则将标签减少 10.

I want to change the text label on a canvas when buttons are clicked. I want to increase the label by 10 if the button "up" is clicked and decrease by 10 if the button "down" is clicked.

这是我的代码,但我不知道下一步该做什么:

This is my code, but I don't know what to do next:

import tkinter as tk

class Sys(tk.Tk, object):
    def __init__(self):
        super(Sys, self).__init__()
        self.title('SYSTEM')
        self.geometry('{0}x{1}'.format(500, 500))   # dimentions
        self.consumtion = 300
        self._build_system() 

    def _build_system(self):
        self.canvas = tk.Canvas(self, bg='lightgreen',  height=500, width=500)   # dimentions
                 '''changeable value'''
        self.cons = self.canvas.create_text(250,250, text = str(self.consumtion))

        '''button'''
        self.but = tk.Button( text = "UP")
        self.but.bind("<Button-1>", lambda event: self.consumption + 10)
        self.but.place(relx=0.8, rely = 0.7, anchor = "center")
        self.but = tk.Button(text = "DOWN")
        self.but.bind("<Button-1>", lambda event: self.consumption - 10)
        self.but.place(relx=0.9, rely = 0.7, anchor = "center")

       # pack all
        self.canvas.pack()

sys=Sys()

推荐答案

您可以使用画布中记录的 itemconfigure 方法来更改画布上任何对象的任何配置选项.

You can use the documented itemconfigure method of the canvas to change any configuration option of any object on the canvas.

例如,您可以编写一个名为 change_consumption 的方法,它接受一个参数来表示值的更改量,并且它可以使用 itemconfigure 来更改出现在画布:

For example, you could write a method named change_consumption that takes a parameter for how much to change the value by, and it can use itemconfigure to change what appears on the canvas:

def change_consumption(self, amount):
    self.consumption += amount
    self.canvas.itemconfigure(self.cons, text=self.consumption)

对于向上"按钮,您可以像这样绑定到此函数;对于向下",您将通过 -10:

You would bind to this function like this for the "up" button; for "down" you would pass -10:

self.but.bind("<Button-1>", lambda event: self.change_consumption(10))

这篇关于画布上的 tkinter 可变值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆