2017-03-30 2 views
1

指定されたテキストのボタンがたくさんあるとします。&ロケーション。どのボタンを表示するか

たとえば、私たちのボタンは{'main'、 'report'、 'memory'、 'bills'、...}です。 ここでは、どのボタンを表示するかを決定する配列があります。

たとえば、z1 = ['report'、 'bill']の場合、この配列の内容は他のボタンになります。あなたのお金で、どのようにコードを書くことができますか?私はすべてのボタンのテキストを "z1"の配列と比較する必要があります、すべてのボタンを定義する前に?ボタンの数が多いので、これは妥当ではありません。

これは私のサンプルコードです:これを行うには

z1=['report','bills','setting'] 

    self.button = Button(self.master,text="memory", command=self.ouvrir) 
    self.button.grid(row=1, column=1) 

    self.button2 = Button(self.master,text="report", command=self.tabluh) 
    self.button2.grid(row=1, column=2) 


    self.button3 = Button(self.master,text="setting", command=self.new_window) 
    self.button3.grid(row=1, column=3) 

    self.button4 = Button(self.master,text="calibration", command=self.cal) 
    self.button4.grid(row=1, column=4) 


    self.button5 = Button(self.master,text="empty weight", command=self.weighing) 
    self.button5.grid(row=1, column=5) 

    self.button6 = Button(self.master,text="bills", command=self.history) 
    self.button6.grid(row=1, column=6) 

    self.button7 = Button(self.master,text="full weight", command=self.full) 
    self.button7.grid(row=1, column=7) 

答えて

0

一つの方法は、値とキーとしてテキストとして辞書にあなたの命令を格納することです。 GUIに表示するキーを含むリストを与えると、彼はこれから正しいキーを選択します。次に、ボタンを動的に作成します。代わりにself.StopButtonを上書きする

敬具、S

from tkinter import * 

class Window: 
    def __init__(self, root,a): 
     self.root = root 
     action = self.find_command(a) 

     for y,element in enumerate(action): 
      self.Make_Button(1,y, element[0], element[1]) 



    def find_command(self, list_): 
     d = {"test": self.printX, "value" : self.printY, "practice" : self.printZ} 
     action = [] 
     for element in list_: 
      for key, value in d.items(): 
       if key == element: 
        action.append([key, value]) 
     return(action) 


    def Make_Button(self, x, y, text_, command_): 
     self.StopButton = Button(self.root, text = text_, command = command_) 
     self.StopButton.grid(row = x, column = y, columnspan = 1, pady=(2,1)) 

    def printX(self): 
     print("testX") 

    def printY(self): 
     print("testY") 

    def printZ(self): 
     print("testZ") 


a = ["test", "practice"] 

root = Tk() 
Window = Window(root,a) 
Window.root.mainloop() 
+0

、私がこれ。あなたが 'SETATTR(自己、ボタン_ '+ text.replace(」」、 "_")、ボタンを]'使用することをお勧めボタンを名前で保存していますので、後で(getattrを使って)アクセスすることができます。もしあなたがその上でアクションを実行したいのであれば、 – arrethra

+0

ありがとう...それはとても良いです...どうすれば固定されたどのボタンの位置(ボタンでもなくてもかまいません) – feri

+0

私はあなたの質問を完全に理解していません。グリッド上の位置?あなたはx座標とy座標を変更します –

関連する問題