问题描述
限时送ChatGPT账号..我需要一个 tkinter 按钮来只打开一个 Toplevel但是我尝试使用一个计数器,当创建一个 Toplevel 和一个 if 循环时它会更改为 2,因此它检查计数器是否为 1,(如果它是 1,它将创建一个 Toplevel 窗口)
I need a tkinter button to open only one Toplevel but I tried using a counter that changes to 2 when one Toplevel is made and a if loop so it checks if the counter is 1, (it will make a Toplevel window if its 1)
但是当我运行程序时,我可以通过多次单击按钮来创建多个窗口
but when I run the program I can make many windows by clicking the button multiple times
我认为使用计数器的解决方案不起作用
I think the solution of using a counter doesn't work
def menu_window(self): # this is in a class
self.frame4 = tk.Frame(self.master, padx=30, pady=30)
self.frame4.grid()
Counter = 1 ### COUNTER
button2 = tk.Button(self.frame4, text="Review your Quiz", command=lambda: PreviewQuiz(self.master, self.frame4,
Counter))
button2.grid(row=3, column=2, padx=40, pady=15, ipadx=28)
button3 = tk.Button(self.frame4, text=" Start your Quiz ")
button3.grid(row=4, column=2, padx=40, pady=5, ipadx=30)
class PreviewQuiz:
def __init__(self, master, frame4, Counter):
if Counter == 1: # CHECK IF COUNTER IS 1
self.master = master
self.review_q = tk.Toplevel(self.master)
self.frame5 = tk.Frame(self.master, padx=50, pady=20)
self.frame5.grid()
self.Counter = 2 # SET COUNTER TO 2
推荐答案
只需在用户点击按钮时禁用该按钮,并仅在顶层关闭时启用它.
Just disable the button when the user clicks on it and enable it only when the top-level is closed.
以下是您在最新帖子中提供的代码的示例:
Here is an example taken from the code you provided in your newest post:
import tkinter as tk
class Run:
def __init__(self, master):
self.master = master
self.button = tk.Button(master, text="TopLevel", command=self.make_new)
self.button.pack()
def make_new(self):
self.button['state'] = 'disabled'
new = tk.Toplevel(self.master)
lbl = tk.Label(new, text='only one topLevel')
lbl.pack()
new.protocol("WM_DELETE_WINDOW", lambda : self.button.configure(state='normal') or new.destroy()) # or make a method to change the state
master1 = tk.Tk()
i = Run(master1)
master1.mainloop()
这篇关于如何让 tkinter 按钮只打开一个顶层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论