2017-08-29 139 views
2

我以Tkinter開始,嘗試使用窗口上方的水平按鈕欄和窗口其餘部分中的條目列表創建簡單的根窗口。Tkinter根窗口類繼承,在__init__中添加小部件

當調試一步一步來,我覺得這條線:

  _button_widget = tk.Button(self.button_bar, title=_button_label) 

使得INIT方法要返回主關閉窗口。 旁註:我看不到任何異常引發(使用Visual Code Studio作爲IDE)和Python 27.如果我刪除按鈕部分窗口創建和顯示。

main.py:

# -*- coding: utf-8 -*- 

import display_commander 

def main(): 
    dc = display_commander.DisplayCommander() 
    dc.mainloop() 

if __name__ == "__main__": 
    main() 

display_commander.py:

# -*- coding: utf-8 -*- 

import Tkinter as tk 

class DisplayCommander(tk.Tk, object): 

    def __init__(self): 
     super(DisplayCommander, self).__init__() 

     self.geometry("350x150+150+150") 

     # Button bar 
     self.button_bar = tk.Frame(self) 
     self.button_bar.config(bg="red") 
     self.button_bar.pack() 

     # Buttons 
     self.buttons = [] 
     for _button_label in ['New Window', 'Delete Window', 'Save Config', 'Load Config']: 
      _button_widget = tk.Button(self.button_bar, title=_button_label) 
      _button_widget.pack() 
      self.buttons.append([_button_label,_button_widget]) 

     # Window List 
     self.window_list = tk.Frame(self) 
     self.window_list.config(bg="yellow") 
     self.window_list.pack() 
+0

此代碼應該肯定會拋出一個異常,這對你會有所幫助。你可能需要看看你的「Visual Code Studio」IDE是如何配置的。 –

回答

2

title參數不能text對按鈕的工作,取代它:

_button_widget = tk.Button(self.button_bar, text=_button_label) 

(我不確定你想如何在代碼中使用self.buttons列表,也許你有更好的字典選項?如果你不需要一個有序的結構存儲,它可以更容易地找到/匹配一個小部件。)

self.buttons = {} 
    [...] 
    self.buttons[_button_label] = _button_widget 
+0

謝謝我無法找到問題。我也很驚訝爲什麼沒有提出異常(或者至少我不能用Visual Code Studio看到它)。關於字典,這是一個非常好的主意,並感謝您繼續提出建議。我不確定是否需要它,一旦我添加按鈕控制器,我甚至可能根本不需要字典或列表。 –

+0

PyCharm拋出一個不錯的'_tkinter.TclError:未知選項「-title」'。擁有自己的存儲空間可能會很方便,但這取決於下一代碼的邏輯 – PRMoureu