我正在嘗試使用 python 3.8 制作游戲,其中我有 1 個畫布/框架和 2 個按鈕。我希望按鈕彼此相鄰,但是每當我運行代碼時,兩個按鈕之間總是有空格。我嘗試使用 pack() 但是當您單擊按鈕時,它會使按鈕位于畫布/框架上方而不是其右側。
我的代碼:
from tkinter import *
# windows, canvas, and frames
root = Tk()
WatchRun = Canvas(root, bg="green", width=600, height=500)
WatchRun.grid(row=0, column=0, rowspan=25)
Upgrade = Frame(root, bg="yellow", width=600, height=500)
Upgrade.grid_forget()
# button functions
def show_upgrade(widget, widget2):
global upgradeBtn
global WatchRunBtn
widget.grid_forget()
widget2.grid(row=0, column=0, rowspan=25)
def show_watchrun(widget, widget2):
global upgradeBtn
global WatchRunBtn
widget.grid_forget()
widget2.grid(row=0, column=0, rowspan=25)
# variables and buttons
distance = 0
started = 0
money = 0
startImage = PhotoImage(file='start.png')
stopImage = PhotoImage(file='stop.png')
upgradeBtn = Button(root, text="Upgrades", width=9, command=lambda: show_upgrade(WatchRun, Upgrade))
upgradeBtn.grid(row=0, column=1)
WatchRunBtn = Button(root, text="Watch run", width=9, command=lambda: show_watchrun(Upgrade, WatchRun))
WatchRunBtn.grid(row=1, column=1)
#loop
root.mainloop()
uj5u.com熱心網友回復:
看來您正試圖用來rowspan嘗試將小部件分開。這不是一個好的解決方案。
雖然有多種方法可以解決按鈕不在一起的問題,但我在這種特定情況下推薦的方法是將您的 GUI 視為具有三行(或者可能是四行,取決于您在調整大小時想要發生的情況)窗戶)。
第 0 行包含第一個按鈕,第 1 行包含第二個按鈕,第 2 行占據 GUI 的其余部分。然后,畫布可以跨越所有三行。
因此,首先向weight第三行添加一個非零值,以便所有未分配的空間都進入它。
root.grid_rowconfigure(2, weight=1)
接下來,將按鈕添加到第 0 行和第 1 行:
upgradeBtn.grid(row=0, column=1)
WatchRunBtn.grid(row=1, column=1)
最后,讓您的畫布跨越所有三行。它將迫使視窗變大,所有額外的空間都分配給第三行。這允許前兩行保留其自然的小高度。
WatchRun.grid(row=0, column=0, rowspan=3)
一個可以說更好的解決方案包括使用pack一兩個額外的框架。UI 似乎顯然有兩個邏輯部分:左側的畫布和右側的一列按鈕。因此,您可以為左側創建一個框架,為右側創建一個框架。然后,將按鈕放在右側框架中,將畫布放在左側框架中。
uj5u.com熱心網友回復:
請參閱我的注釋,指出代碼中的更改。如果您對此有任何疑問,請告訴我。您可能會發現此問答也很有幫助。PEP 8
import tkinter as tk #no wildcard imports
#free functions under imports to ensure function is defined
def show_frame(widget, widget2):
'''common function for upgrade_btn and watchrun_btn
- packs the appropiated widget in the left_frame'''
widget.pack_forget()
widget2.pack()
distance = 0
started = 0
money = 0
#variable names lowercase
root = tk.Tk()
#split window in two containers/master/frames
left_frame = tk.Frame(root)
right_frame= tk.Frame(root)
#leftframe content
watchrun = tk.Canvas(left_frame, bg="green", width=600, height=500)
upgrade = tk.Frame(left_frame, bg="yellow", width=600, height=500)
#rightframe content
upgrade_btn = tk.Button(right_frame, text="Upgrades", width=9, command=lambda: show_frame(watchrun, upgrade))
watchrun_btn = tk.Button(right_frame, text="Watch run", width=9, command=lambda: show_frame(upgrade, watchrun))
#geometry management
left_frame.pack(side=tk.LEFT)
right_frame.pack(side=tk.RIGHT,fill=tk.Y)
watchrun.pack()
upgrade_btn.pack()
watchrun_btn.pack()
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400996.html
上一篇:enterned_text=enterned_text.get()UnboundLocalError:賦值前參考了區域變數“enterned_text”
