Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在tkinter中创建标签,并使用int变量更新标签_Python_Python 3.x_Tkinter - Fatal编程技术网

Python 在tkinter中创建标签,并使用int变量更新标签

Python 在tkinter中创建标签,并使用int变量更新标签,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,我想创建一个标签,并用int值更新它,按下按钮也会更新标签中的int值。我还是Python新手,希望得到一些帮助: import tkinter as tk class Main(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.integer = tk.IntVar() self.integer.set(0) tk.Button(self, text='Qui

我想创建一个标签,并用int值更新它,按下按钮也会更新标签中的int值。我还是Python新手,希望得到一些帮助:

import tkinter as tk

class Main(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        self.integer = tk.IntVar()
        self.integer.set(0)

        tk.Button(self, text='Quit', command=self.destroy).pack()
        tk.Button(self, text='+', command=self.plus_one).pack()
        tk.Button(self, text='-', command=self.take_one).pack()

        self.entry0 = tk.Entry(self, textvariable=str(self.integer), justify="center", width=4)
        self.entry0.pack()

    def plus_one(self):
        x =  self.integer.get() + 1
        self.integer.set(x)

    def take_one(self):
        x =  self.integer.get() - 1
        self.integer.set(x)

app = Main()
app.mainloop()

您可以使用与Entry小部件相同的方法执行此操作:


根据您的意见,如果您有兴趣在按下按钮而不是释放按钮时进行绑定,这一点已经得到解决。

问题是什么?代码似乎运行良好。虽然导入的as数字位与直觉相反。我会使用import tkinter作为tk,并相应地重构代码。你可以用tk替换数字:我的问题是如何创建一个标签,在这个标签中,只要我按下+和-按钮,Int值就会更新。然后也许你应该相应地更新你的问题。简单地说,是关于按钮按下还是按钮释放的问题?对我来说,代码在按键时工作,但更新发生在按钮释放时。
import tkinter as tk

class Main(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        self.integer = tk.IntVar()
        self.integer.set(0)

        tk.Button(self, text='Quit', command=self.destroy).pack()
        tk.Button(self, text='+', command=self.plus_one).pack()
        tk.Button(self, text='-', command=self.take_one).pack()

        self.entry0 = tk.Entry(self, textvariable=str(self.integer), justify="center", width=4)
        self.entry0.pack()

        self.label0 = tk.Label(self, textvariable=str(self.integer))
        self.label0.pack()

    def plus_one(self):
        x =  self.integer.get() + 1
        self.integer.set(x)

    def take_one(self):
        x =  self.integer.get() - 1
        self.integer.set(x)

app = Main()
app.mainloop()