我正在嘗試從 Tkinter 創建一個簡單的“SOS”益智游戲。我正在使用 grid 方法創建一個條目小部件網格。現在我想要為每個條目分配一個變數。我嘗試使用 for 回圈來執行此操作,但無法以正確的方式使用該變數。你能幫助我嗎?我的問題想法解釋如下圖,

代碼
for i in range(5):
for j in range(5):
self.entry=Entry(root,textvariable=f'{i}{j}')
self.entry.grid(row=i,column=j)
self.position.update({f"{i}-{j}":f"{i}{j}"})
enter code here
uj5u.com熱心網友回復:
您應該將制作的小部件存盤到串列或字典中,而不是隨時隨地創建變數。該串列似乎更合理,因為您可以更輕松地對其進行索引。
下面是一個簡單但完整的示例,展示了如何制作二維串列以及在此串列中搜索條目物件:
from tkinter import * # You might want to use import tkinter as tk
root = Tk()
def searcher():
row = int(search.get().split(',')[0]) # Parse the row out of the input given
col = int(search.get().split(',')[1]) # Similarly, parse the column
obj = lst[row][col] # Index the list with the given values
print(obj.get()) # Use the get() to access its value.
lst = []
for i in range(5):
tmp = [] # Sub list for the main list
for j in range(5):
ent = Entry(root)
ent.grid(row=i,column=j)
tmp.append(ent)
lst.append(tmp)
search = Entry(root)
search.grid(row=99,column=0,pady=10) # Place this at the end
Button(root,text='Search',command=searcher).grid(row=100,column=0)
root.mainloop()
你必須輸入一些行和列,比如0,0第一行,第一列,然后按下按鈕。確保條目中沒有空格。您不必太擔心搜索部分,因為您可能需要其他一些邏輯。但是不要在旅途中創建變數,您應該使用這種方法并將其存盤在容器中。
另請注意,您不必使用,textvariable因為這里完全不需要這些。你可以對它的原始物件做任何你想做的事情Entry。只需確保串列索引從 0 開始,而不是從 1 開始(或從給定的正常值中減去 1)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335954.html
上一篇:在Tkinter中回圈放置影像
