问题描述
我有另一个问题,关于我正在用 Python tkinter 编写的一些扑克游戏代码。我的 GUI 中有许多按钮,但有些按钮不应在其他按钮之前按下,而有些按钮只能按下一定的最大次数。我可以创建全局“点击计数”变量。但是我了解到应该谨慎使用 global 。是否有另一种方法可以使按钮仅在满足某些条件时才起作用? 这是一些精简的代码:
from tkinter import *
x = Tk()
x.state('zoomed')
def lay():
card1.place(relx=0.2,rely=0.2)
card2.place(relx=0.4,rely=0.2)
def bet():
print('BET should only be pressed after LAY CARDS,and max twice')
card1 = Label(x,text='card1')
card2 = Label(x,text='card2')
Button(x,text='LAY CARDS',command=lay).place(relx=0.2,rely=0.5)
Button(x,text='BET',command=bet).place(relx=0.4,rely=0.5)
x.mainloop()
总的来说,我开始编写这段代码只是作为一个挑战,而 GUI 并不是最重要的部分。但是,开始后,我想让它完全正常工作。我发现虽然 Python 上有丰富的资源,但缺乏关于 Tkinter 的有用信息,特别是对于我想创建的那种交互式代码(“交互式”是指代码中的代码,其中有几个按钮,每个按钮产生不同的应按特定顺序执行的一系列操作)。有没有人知道一本用非常适合初学者的术语编写的关于使用 Tkinter 的好书?
解决方法
按钮的状态可以通过其他按钮点击设置为正常/禁用。 count 变量可以放在一个闭包中,让它被保留和更新 但不是对应用程序是全局的。
另一种方法是为计数器创建一个类,并将命令函数作为使用面向对象编程的方法。
下注按钮被禁用,直到点击下注。下注功能禁用下注并启用下注。下注功能在两次点击后禁用下注。
import tkinter as tk
x = tk.Tk()
x.state('zoomed')
def lay():
card1.place(relx=0.2,rely=0.2)
card2.place(relx=0.4,rely=0.2)
# Set bet_button to NORMAL after lay is clicked
bet_button.config( state = tk.NORMAL )
lay_button.config( state = tk.DISABLED ) # lay DISABLED
def make_bet():
# Returns a function making a closure.
# count can be 'seen' by bet but is not global.
count = 0
def bet():
nonlocal count
count += 1
print( 'BET pressed {} times.'.format(count) )
if count > 1:
bet_button.config( state = tk.DISABLED )
return bet
card1 = tk.Label(x,text='card1')
card2 = tk.Label(x,text='card2')
lay_button = tk.Button(x,text='LAY CARDS',command=lay)
lay_button.place(relx=0.2,rely=0.5)
bet_button = tk.Button(x,text='BET',command=make_bet(),state = tk.DISABLED)
# make_bet requires the brackets as it returns the appropriate function
bet_button.place(relx=0.4,rely=0.5)
x.mainloop()