3

次の入力ボックスがあり、値を取得したため、textvariableのリストオプションを入力しました。

ただし、デフォルトのテキストを背景に配置して、各ボックスに必要な値(グレースケールテキスト、値1、値2など)を表示できるかどうか疑問に思いました。

self.numbers = [StringVar() for i in xrange(self.number_boxes) ] #Name available in global scope.       
box=Entry(self.frame_table,bg='white',borderwidth=0, width=10, justify="center", textvariable=self.numbers[i])

ボックス内でマウスをクリックしたときに「textvariable」を変更するものを追加できますか、それとも単に別のtextvariableまたはtextを追加して、デフォルトのテキストを設定できますか?

  self.box = []

  for i in xrange(self.number_boxes):

        self.clicked = False
        self.box.append(Entry(self.frame_table,bg='white',borderwidth=0, width=10, justify="center", textvariable=self.numbers[i], fg='grey'))
        self.box[i].grid(row=row_list,column=column+i, sticky='nsew', padx=1, pady=1) 
        self.box[i].insert(0, "Value %g" % float(i+1))
        self.box[i].bind("<Button-1>", self.callback)
4

1 に答える 1

4

ウィジェットにデフォルトのテキストを配置するには、ここで説明する方法をEntry使用できます。insert()

box.insert(0, "Value 1")    # Set default text at cursor position 0.

boxここで、ユーザーがボックス内でマウスクリックを実行した後に内容を変更するには、イベントをオブジェクトにバインドする必要があります。Entryたとえば、次のコードは、ボックスがクリックされたときにボックスの内容を削除します。(ここでイベントとバインディングについて読むことができます。)以下に、この完全な例を示します。

clickedボックス内のテキストの削除は、おそらく最初のクリック(つまり、デフォルトのコンテンツを削除する場合)でのみ実用的であるため、クリックされたかどうかを追跡するためにグローバルフラグを作成しました。

from tkinter import Tk, Entry, END    # Python3. For Python2.x, import Tkinter.

# Use this as a flag to indicate if the box was clicked.
global clicked   
clicked = False

# Delete the contents of the Entry widget. Use the flag
# so that this only happens the first time.
def callback(event):
    global clicked
    if (clicked == False):
        box[0].delete(0, END)         #  
        box[0].config(fg = "black")   # Change the colour of the text here.
        clicked = True

root = Tk()
box = []                              # Declare a list for the Entry widgets.

box.append(Entry(fg = "gray"))        # Create an Entry box with gray text.
box[0].bind("<Button-1>", callback)   # Bind a mouse-click to the callback function.
box[0].insert(0, "Value 1")           # Set default text at cursor position 0.

box.append(Entry(fg = "gray"))        # Make a 2nd Entry; store a reference to it in box.
box[1].insert(0, "Value 2")

box[0].pack()                         #
box[1].pack()

if __name__ == "__main__":
    root.mainloop()
于 2012-07-05T03:59:17.783 に答える