from tkinter import *
window2 = Tk()
Var = ' '
store = ['a', 'b', 'c', 'd']
count = 3
for i in store:
if i != None:
chs_store = Button(window2, text = i).grid(row = count , column = 4)
count = 1
我制作了按鈕并將它們放在這樣的框架上。為了放置按鈕與串列的順序相同。現在我想將不同的命令放入每個按鈕。
ex) 如果我點擊顯示“a”的按鈕,我想要Var = 'one',如果我點擊按鈕“b”,我想要Var = 'two'。
我該如何解決這個問題
uj5u.com熱心網友回復:
將每個命令功能放在類似于您正在使用的串列中store
# define the functions you want your buttons to call up here, e.g.:
def func_a():
print('hello!')
# note: no parentheses () since you're not calling these functions here!
commands = [func_a, func_b, func_c, func_d]
store = ['a', 'b', 'c', 'd']
count = 3
for index, i in enumerate(store):
if i != None:
chs_store = Button(window2, text=i, command=commands[index])
# place your buttons on the grid in a separate line since 'grid' returns
# None, which means chs_store will have no value anyway
chs_store.grid(row=count, column=4)
count = 1
uj5u.com熱心網友回復:
僅基于提供的代碼,您可以為所選專案的位置store定義另一個串列:
store = ["a", "b", "c", "d"]
position = ["one", "two", "three", "four"]
然后在點擊某個按鈕時列印相應的位置。
下面是修改后的代碼:
from tkinter import *
window2 = Tk()
Var = ' '
store = ['a', 'b', 'c', 'd']
position = ['one', 'two', 'three', 'four']
def update_var(pos):
global Var
Var = pos
print(f"{Var=}")
count = 3
for i, pos in zip(store, position):
Button(window2, text=i, command=lambda pos=pos: update_var(pos)).grid(row=count, column=4)
count = 1
window2.mainloop()
uj5u.com熱心網友回復:
如果你列印出 chs_store 你會看到 None,因為你沒有存盤按鈕物件,而是網格方法的結果。因此,最好將它們分開。為了不做計數器,我使用了enumerate函式。我將需要附加到按鈕的功能放在一個元組中。
from tkinter import *
def fun_a():
global Var
Var = 'a'
print('Var = ', Var)
def fun_b():
global Var
Var = 'b'
print('Var = ', Var)
def fun_c():
global Var
Var = 'c'
print('Var = ', Var)
def fun_d():
global Var
Var = 'd'
print('Var = ', Var)
window2 = Tk()
Var = ' '
funs = (fun_a, fun_b, fun_c, fun_d)
store = ('a', 'b', 'c', 'd')
btns = []
for i, st in enumerate(store):
b = Button(window2, text=st, command=funs[i])
b.grid(row=i, column=4)
btns.append(b)
print(btns)
window2.mainloop()
[<tkinter.Button object .!button>, <tkinter.Button object .!button2>, <tkinter.Button object .!button3>, <tkinter.Button object .!button4>]
Var = a
Var = b
Var = c
Var = d
如果您不需要為每個按鈕提供單獨的功能,則可以縮短代碼。我將按鈕保存在一個串列中,因為變數 b 在回圈的每次迭代中都會被覆寫。
from tkinter import *
from functools import partial
def fun(s):
global Var
Var = s
print('Var = ', Var)
window2 = Tk()
Var = ' '
store = ('a', 'b', 'c', 'd')
btns = []
for i, st in enumerate(store):
b = Button(window2, text=st, command=partial(fun, st))
b.grid(row=i, column=4)
btns.append(b)
window2.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/534976.html
