我正在使用 Python 和 Tkinter 創建世界杯抽獎活動,我想要兩個按鈕;一個從人員串列中選擇一個隨機人的按鈕,另一個從團隊串列中選擇一個隨機世界杯球隊的按鈕。每次選擇其中一個時,都應將其從串列中洗掉,以免再次被選中。我還想要一個清除按鈕,洗掉最后選擇的球員和球隊。清除按鈕似乎可以作業,但在選擇下一個人和團隊時,它有時會選擇以前選擇過的人,因此不起作用。
from tkinter import *
import random
root = Tk()
root.title('World Cup 2022 - Sweepstake')
root.geometry("600x800")
def select_player():
global player_label
players = ["Matt", "Steve", "Dave", "Pete"]
chosen_player = players.pop(random.randrange(len(players)))
player_label = Label(root, text=chosen_player, font=("Arial", 16, 'bold'))
player_label.pack(pady=30)
return
def select_team():
global team_label
teams = ["Qatar", "Ecuador", "Senegal", "Netherlands"]
teams = teams.pop(random.randrange(len(teams)))
team_label = Label(root, text=teams, font=("Arial", 22, 'bold'))
team_label.pack(pady=40)
return
def clear_label():
player_label.pack_forget()
team_label.pack_forget()
top_label = Label(root, text="World Cup Sweepstake", font=("Arial", 22, 'bold'))
top_label.pack(pady=20)
select_player_button = Button(root, text="Select Player", font=("Arial", 14), command=select_player)
select_player_button.pack(pady=15)
select_team_button = Button(root, text="Select Team", font=("Arial", 14), command=select_team)
select_team_button.pack(pady=15)
delete_button = Button(root, text="Clear", command=clear_label)
delete_button.pack(pady=20)
root.mainloop()
uj5u.com熱心網友回復:
球員和球隊名單應該定義在函式之外。使用下面的代碼:
from tkinter import *
import random
def select_player():
global players,player_label
select_player_button.config(state="disabled")
select_team_button.config(state="active")
chosen_player = players.pop(random.randrange(len(players)))
player_label = Label(root, text=chosen_player, font=("Arial", 16, 'bold'))
player_label.pack(pady=30)
def select_team():
global teams,team_label
select_team_button.config(state="disabled")
delete_button.config(state="active")
chosen_team = teams.pop(random.randrange(len(teams)))
team_label = Label(root, text=chosen_team, font=("Arial", 22, 'bold'))
team_label.pack(pady=40)
def clear_label():
global players
delete_button.config(state="disabled")
if(len(players)>1):
select_player_button.config(state="active")
player_label.pack_forget()
team_label.pack_forget()
teams = ["Qatar", "Ecuador", "Senegal", "Netherlands"]
players = ["Matt", "Steve", "Dave", "Pete"]
root=Tk()
top_label = Label(root, text="World Cup Sweepstake", font=("Arial", 22, 'bold'))
top_label.pack(pady=20)
select_player_button = Button(root, text="Select Player", font=("Arial", 14), command=select_player)
select_player_button.pack(pady=15)
select_team_button = Button(root,state="disabled", text="Select Team", font=("Arial", 14), command=select_team)
select_team_button.pack(pady=15)
delete_button = Button(root,state="disabled", text="Clear", command=clear_label)
delete_button.pack(pady=20)
root.mainloop()
玩得開心 :)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/523443.html
上一篇:如何在列印新標簽之前洗掉標簽
