【问题标题】:I want to increase a variable whenever I click a button in tkinter每当我单击 tkinter 中的按钮时,我都想增加一个变量
【发布时间】:2021-08-26 21:45:02
【问题描述】:

大家好,请问我正在使用此代码,我希望它增加 当我单击按钮时名为compteur 的变量,我希望它在__init__ 函数中增加。

但问题是这个变量总是保持为 0

import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image

class MainUi(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.geometry("300x400")
        self.geometry("+500+100")
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
    
        self.frames = {}
        frame = StartPage(container, self)
        self.frames[StartPage] = frame
        frame.place(relx=0, rely=0, relwidth=1, relheight=1)




class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.configure(background='white')
        # self.master.configure(background='black')
        self.compteur = 0
        button1 = ttk.Button(self, text="Next", width=7, command = lambda: self.next_clicked())
        button1.place(relx=0.8, rely=0.9)  

        print(self.compteur)

    def next_clicked(self):
        self.compteur += 1
        
app = MainUi()
app.mainloop()

【问题讨论】:

  • 你需要一个类属性;您实现了一个实例属性,每次创建实例时都将其重置为 0。由于您没有明确指定所需的功能,因此很难为您找到维修。
  • 每当点击Next 按钮时,您的代码确实增加了self.compteur。更好地说明 "i want it to be increased in the __init__ function" 是什么意思。请注意,__init__() 对于类的每个实例只会执行一次。

标签: python class tkinter


【解决方案1】:

问题不在于没有引发self.compteur,而是将打印引发值的print(self.compteur) 语句放置在next_clicked(self) 方法之外。这应该有效:

def next_clicked(self):
    self.compteur += 1
    print(self.compteur)

【讨论】:

  • 是的,它是这样工作的,但我需要在 init 函数中更改它,因为我需要在某些标签中使用它
  • self.compteur += 1 更改self.compteur 类的对象的self.compteur 属性StartPage 类。在您的情况下,这是frame。但是,这不会自动更改标签,因为之前使用了 frame.compteurtext 参数。
猜你喜欢
  • 1970-01-01
  • 2019-11-02
  • 2019-09-22
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多