我在這里有一種情況,我想按下按鈕并添加影像。我已經成功地獲得了第一個影像,但是當我按下按鈕添加下一個影像時,它只會將其堆疊在頂部。有沒有一種方法可以在每次按下按鈕停止堆疊時移動新條目的位置?
images = []
def add_friend():
x = 0
x = 1
global friendImage
friendFrame.filename = filedialog.askopenfilename(initialdir= "/coursework - current/images/", title= "Select a friend",)
friendImage = ImageTk.PhotoImage(Image.open(friendFrame.filename).resize((100,150), Image.NEAREST))
friendImageInsert = Label(friendFrame, image=friendImage)
friendImageInsert.grid(row= 0, column=x, sticky="NW")
friendImageLabel = Label(friendFrame, text=friendFrame.filename.split("/")[-1])
friendImageLabel.grid(row= 1, column=x)
images.append(friendImageInsert)
images.append(friendImageLabel)
所以這就是它現在的樣子:

如果我要打開一個新影像并將其放入。我怎樣才能讓它以相同的格式將下一個影像放在它旁邊的列中?我希望它將它放在我添加的每個新列中
uj5u.com熱心網友回復:
首先,您需要創建x一個全域變數并在函式外部對其進行初始化。其次,您不應該friendImage對添加的所有影像使用相同的全域變數,因為它會使先前添加的影像被垃圾收集。使用標簽的屬性來存盤影像。您也可以將檔案名和影像放在一個標簽而不是兩個標簽中。
labels = []
x = 0
def add_friend():
global x
filename = filedialog.askopenfilename(initialdir="/coursework - current/images/", title="Select a friend")
image = ImageTk.PhotoImage(Image.open(filename).resize((100,150), Image.NEAREST))
filename = os.path.basename(filename)
friendImageLabel = Label(friendFrame, compound="top", image=image, text=filename, bd=1, relief='raised')
friendImageLabel.grid(row=0, column=x, sticky="nsew")
friendImageLabel.image = image # save a reference of image to avoid garbage collected
labels.append(friendImageLabel)
x = 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441025.html
標籤:Python tkinter tkinter 布局 tkinter 按钮
上一篇:tkinter圓形按鈕有白色邊框
