簡體   English   中英

使用Tkinter將小部件定位在框架上

[英]Positioning widgets on frames with Tkinter

因此,我對Python和Tkinter並不陌生。 我正在制作《戰艦》游戲。 到目前為止,我已經成功創建了一個按鈕網格。 我現在正在嘗試在此游戲手柄的右側創建一個菜單。 我試圖通過在窗口中使用兩個不同的框架來實現此目的-一個是游戲手柄所在的框架,另一個是我具有菜單(位於標簽下方)的框架。 無論我在cheat_button.grid()里面放什么,我似乎都無法更改此按鈕的位置。 它只是停留在menu_frame框架的左上角。 我還想在該框架下添加另一個按鈕,並在同一幀的下方添加一個消息框。 有什么建議么? 我已經鏈接了我認為相關的部分代碼。

謝謝。

col_tot = 10
row_tot = 10

self.grid_frame = tk.Frame(self)
self.grid_frame.grid(row=0, column=0, rowspan=row_tot, columnspan=col_tot, sticky = "WENS")

self.menu_frame = tk.Frame(self, bg="grey", bd=1, relief="ridge")
self.menu_frame.grid(row=1, column=col_tot, rowspan=row_tot-1, columnspan=4, sticky = "WENS")


button_no = 0


self.button_list = []   
for x in range(row_tot):            
  self.button_list.append([""] * col_tot)


for i in range(row_tot):

  for j in range(col_tot):

    self.button_list[i][j] = (tk.Button(self.grid_frame, height = 3, width = 6, text = str(button_no + 1),
      activebackground = "yellow", relief = "groove"))
    self.button_list[i][j]["command"] = lambda i=i, j=j:self.update_colour(i, j)
    self.button_list[i][j].grid(row = i, column = j, sticky = "NW")

    button_no += 1

self.welcome = tk.Label(self, text = "Welcome to Battleship!",
  fg = "red", bg = "grey", font = ("Helvetica", 12), relief="ridge")
self.welcome.grid(row = 0, column = col_tot, columnspan = 4, sticky = "WENS")


self.cheat_button = tk.Button(self.menu_frame, text = "Cheat")
self.cheat_button.grid()
self.cheat_button.config(bg = "grey")

如果行和列為空並且未配置為具有最小大小,則其大小為零。 同樣重要的是要知道每個框架都有自己的“網格”,因此即使左側框架有10行和10列,右側框架也完全是空的。

如果希望按鈕在框架中居中,一種解決方法是在其上方和下方保留一個空行,並配置這些行以使其具有任何額外的空間。 例如:

self.welcome.grid(row = 0, column = 0, sticky = "WENS")
# notice we've put nothing in rows 1 or 3
self.cheat_button.grid(row=2, column=0)

self.menu_frame.grid_rowconfigure(1, weight=1)
self.menu_frame.grid_rowconfigure(3, weight=1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM