我正在尝试获取以下代码的最后几行,以便在按下原始的6个按钮之一时调用相应的功能来重命名按钮。我已经尝试将命令行更改为按钮[0] .command = Pistols()。我也尝试使用带有变量(如x == 1)的if循环来确定如果按下按钮x然后为1并且for循环将调用函数Pistols,但没有成功。但是按钮会自动调用该功能并将第一个按钮重命名为“.44 Pistol”而不是它应该是“Pistols”。我不想执行命令并在按下时调用该函数。我知道tkinter会自动查看被调用的函数并运行它的代码。我怎么能延迟这个或以另一种方式解决这个问题,让函数代码只在按下时执行。提前致谢!
from tkinter import *
buttons = []
clm = [1,2,1,2,1,2]
rw = [1,1,2,2,3,3]
btnmain_list = ['Pistol','Rifle','Assult Rifle','Submachine Gun','Heavy Weapon','Plasma Weapons']
btnpistol_list = ['.44 Pistol', '10mm Pistol', 'Pipe Bolt-Action Pistol','Flare Gun', 'Pipe Pistol', 'Pipe Revolver']
btnrifle_list = []
btnasrifle_list = []
btnsubgun_list = []
btnheavy_list = []
btnplasma_list = []
ms = Tk()
ms.title('Fallout 4 weapon mods and needed materials')
ms.geometry('450x400')
placement = Frame(ms)
placement.grid()
class Guns:
def Pistols ():
buttons[0] = Button(placement,height = '5',width = '20', text = btnpistol_list[0])
buttons[0].grid(column = clm[0], row = rw[0])
def Rifles ():
x = 0
def AssultRifles ():
x = 0
def SubmachineGuns ():
x = 0
def HeavyWeapons ():
x = 0
def PlasmaWeapons ():
x = 0
for i in range (6):
b = Button(placement,height = '5',width = '20', text = btnmain_list[i])
b.grid(column = clm[i], row = rw[i])
buttons.append(b)
buttons[0].command = Pistols()
答案 0 :(得分:1)
我通过将课程改为此来找到解决方案:
class Guns:
global counter
counter = 0
def pistolCycle():
global counter
buttons[0].config(text=btnpistol_list[counter])
if counter == len(btnpistol_list)-1:
counter=0
counter = counter+1
def Pistols ():
buttons[0] = Button(placement, height = '5',width = '20', text="Pistols", command = lambda: Guns.pistolCycle() )
buttons[0].grid(column = clm[0], row = rw[0])
def Rifles ():
x = 0
def AssultRifles ():
x = 0
def SubmachineGuns ():
x = 0
def HeavyWeapons ():
x = 0
def PlasmaWeapons ():
x = 0
for i in range (6):
b = Button(placement,height = '5',width = '20', text = btnmain_list[i])
b.grid(column = clm[i], row = rw[i])
buttons.append(b)
Pistols()
所以,这里是发生了什么的细分:
现在,使用全局变量可能会变得混乱。我已经为您提供了基本框架,因此您可以使用自己的逻辑来获取变量" counter"每次进入pistolCycle(EG,pistolCycle(counter))
您需要创建一个单独的计数器和循环功能,以便所有按钮都能正常工作。
我希望这有帮助!!
PS:pistolCycle函数中的if语句意味着当它不存在于列表中时它不会尝试获取项目。