我想结合使用def clicked和def clicked2的功能,因为它们是相同的,但是我不知道该怎么做。我还没有尝试过,但我想不出一种方法。
from tkinter import *
import random
window = Tk()
x = round(random.random()) + 1
m = 7
window.title("NIM-7 spel")
window.geometry('350x200')
lbl = Label(window, text="Player " + str(x) + " next")
lbl2 = Label(window, text="Their are " + str(m) + " coins left")
lbl.grid(column=0, row=1)
lbl2.grid(column=1, row=0)
def clicked():
global x
global m
m -= 1
if m < 1:
lol = "Player " + str(x) + " won!"
res = ""
else:
if x == 1:
x = 2
else:
x = 1
lol = "Their are " + str(m) + " coins left"
res = "Player " + str(x) + " is next"
lbl.configure(text=res)
lbl2.configure(text=lol)
def clicked2():
global x
global m
m -= 2
if m < 1:
lol = "Player " + str(x) + " won!"
res = ""
else:
if x == 1:
x = 2
else:
x = 1
lol = "Their are " + str(m) + " coins left"
res = "Player " + str(x) + " is next"
lbl.configure(text=res)
lbl2.configure(text=lol)
btn1 = Button(window, text="Take 1 coin", command=clicked)
btn2 = Button(window, text="Take 2 coins", command=clicked2)
btn1.grid(column=1, row=1)
btn2.grid(column=2, row=1)
window.mainloop()
有人知道怎么做吗?
答案 0 :(得分:1)
如果使用lambda函数,则可以向tkinter按钮添加参数。 已经问了一些相同的问题:
How to call a function with arguments in "Button" function from "tkinter" python package?
def clicked(value):
global x
global m
m -= value
if m < 1:
lol = "Player " + str(x) + " won!"
res = ""
else:
if x == 1:
x = 2
else:
x = 1
lol = "Their are " + str(m) + " coins left"
res = "Player " + str(x) + " is next"
lbl.configure(text=res)
lbl2.configure(text=lol)
btn1 = Button(window, text="Take 1 coin", command = lambda:clicked(1))
btn2 = Button(window, text="Take 2 coins", command = lambda:clicked(2))
答案 1 :(得分:0)
传入要减少m
的参数作为参数。所以:
def clicked(decrement):
global x
global m
m -= decrement
if m < 1:
lol = "Player " + str(x) + " won!"
res = ""
else:
if x == 1:
x = 2
else:
x = 1
lol = "Their are " + str(m) + " coins left"
res = "Player " + str(x) + " is next"
lbl.configure(text=res)
lbl2.configure(text=lol)
然后这样命名:clicked(1)
和clicked(2)
。
由于将其作为参数传递给Button
,因此可以创建虚拟函数:
def clicked1():
clicked(1)
以及clicked2
的类似内容。