每当我在tkinter中单击一个按钮时,我想增加一个变量

2024-06-28 19:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

Hello guys, please I'm using this code and I want it to increase a variable named compteur when I click in the button, I want it to be increased in the __init__ function.

but the problem is that this variable stays always to 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()

Tags: thetoimportselfinitcontainerdefit
1条回答
网友
1楼 · 发布于 2024-06-28 19:31:56

问题不是没有提出self.compteur,而是将打印提出的值的print(self.compteur)语句放在next_clicked(self)方法之外。这应该起作用:

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

相关问题 更多 >