簡體   English   中英

使用 tkinter 的 Python GUI 編程

[英]Python GUI programing using tkinter

我有一個包含多行的表單。 按回車鍵會打開一個選項窗口。 但是每次我按回車鍵都會打開一個新的選項窗口。 我如何控制和檢查選項窗口是否打開然后不打開選項窗口。

import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import messagebox

# Directory/File processing libraries
import os
import configparser
import csv

def callback():
    #messagebox.showinfo("Netezza", Folder_Name_var.get())
    #messagebox.showinfo("Netezza", Table_Name_var.get() )
    config = configparser.ConfigParser()
    config.read('C:\\aa\\config.ini')
    #for value in config['Folder']: print(value)
    for key in config.items('Folder'):
        print (key[1].replace('{Folder_Name}',Folder_Name_var.get()))
        os.makedirs(key[1].replace('{Folder_Name}',Folder_Name_var.get()),exist_ok=True)

def click_tv(event):
    #messagebox.showinfo("Inside")
    selected=trv.focus()
    print(trv.item(selected))

def press_enter(event):
    #messagebox.showinfo("Inside")
    selected=trv.focus()
    print(trv.item(selected))
    print(str((event.keysym)))
    if str((event.keysym))=='Return':
        option_wnd=Toplevel(root)
        option_wnd.geometry('200x200')
        option_wnd.title('Option Window')
        option_wnd.grab_set()
        #option_wnd.pack()
def selection_change(event):
    selected = trv.selection()[0]
    print('You clicked on', trv.item(selected))
    #option_wnd.mainloop()
root = Tk()

Folder_Name_var = tk.StringVar()
Table_Name_var = tk.StringVar()

# This is the section of code which creates the main window
root.geometry('873x498')
root.configure(background='#63B8FF')
root.title('Automation Software - Blue Shield of California')

pic= Canvas(root, height=100, width=100)
#pic= Canvas(root, height=225, width=580)

#picture_file = PhotoImage(file = 'c:\\aa\\bsc.png')
#pic.create_image(0, 0, anchor=NW, image=picture_file)
#pic.place(x=5, y=5)


lbl_Folder_Name = Label(root, text="Folder Name",background='#63B8FF').place(x=600, y=50)
lbl_Table_Name = Label(root, text="Table Name",background='#63B8FF').place(x=600, y=90)

txt_Folder_Name = Entry(root,textvariable = Folder_Name_var).place(x=700, y=50)
txt_Table_Name = Entry(root,textvariable = Table_Name_var).place(x=700, y=90)

Button(root, text="Show", width=10, command=callback).place(x=700,y=120)

tree_frame=Frame(root)
tree_frame.place(x=10,y=260)

tree_scroll=Scrollbar(tree_frame)
tree_scroll.pack(side=RIGHT,fill=Y)

style=ttk.Style()
style.theme_use("default")
style.map("Treeview",background=[('selected','bisque2')],foreground=[('selected','black')])

trv= ttk.Treeview(tree_frame,yscrollcommand=tree_scroll.set, columns=(1,2,3), show="headings", height="10")
trv.heading(1,text="Parameter", anchor=W)
trv.heading(2,text=" Parameter  Description", anchor=W)
trv.heading(3,text=" Specify your value", anchor=W)
trv.tag_configure('even',background="white")
trv.tag_configure('odd',background="steelblue")
trv.bind("<Double-1>",click_tv)
trv.bind("<Return>",press_enter)
trv.bind("<<TreeviewSelect>>",selection_change)
trv.pack()
tree_scroll.config(command=trv.yview)


i=1

with open("c:\\aa\control.txt") as options:
    options_line = csv.reader(options, delimiter='\t')
    for option in options_line:
        #a=1
        if i%2==0:
            trv.insert(parent='', index='end', values=(option), tags=('even',))
            #print("even")
        else:
            trv.insert(parent='', index='end', values=(option), tags=('odd',))
            #print("odd")
        i=i+1
#trv.place(x=100,y=260)


root.mainloop()

每次我在根窗口上按 Enter 鍵時,它都會打開一個彈出窗口。 我需要控制它。 如果彈出窗口是打開的,那么我們不應該允許另一個彈出窗口打開。 在此處輸入圖片說明

直接的方法是使用winfo_exists()

root.option_wnd = None # Init value

def press_enter(event):
    #messagebox.showinfo("Inside")
    selected=trv.focus()
    print(trv.item(selected))
    print(str((event.keysym)))
    if str((event.keysym))=='Return': 
        if root.option_wnd and root.option_wnd.winfo_exists():
            root.option_wnd.lift() # make this window on the top.
        else: # create this window
            root.option_wnd  = tk.Toplevel(root)
            .....

但是我不認為每次用戶鍵入Enter時都需要創建此窗口。在開始時創建它,只需在用戶鍵入Enter時顯示它

例如:

root = tk.Tk()
option_wnd = tk.Toplevel()
option_wnd.wm_protocol("WM_DELETE_WINDOW", option_wnd.withdraw) # when user try to close this window, hide it instead of destroy it
.....


option_wnd.withdraw() # hide this window

def press_enter(event):
    #messagebox.showinfo("Inside")
    selected=trv.focus()
    print(trv.item(selected))
    print(str((event.keysym)))
    if str((event.keysym))=='Return': 
        option_wnd.deiconify() # show it.

如果您不使用類,您可以執行以下操作:

options_displayed = False #global

def option_closed(w):
    global options_displayed
    w.destroy() #close the actual window
    options_displayed = False # log the fact it is now close

def press_enter(event):
    global options_displayed # reference global variable
    #messagebox.showinfo("Inside")
    selected=trv.focus()
    print(trv.item(selected))
    print(str((event.keysym)))
    if str((event.keysym))=='Return' and not options_displayed:
        option_wnd=Toplevel(root)
        option_wnd.geometry('200x200')
        option_wnd.title('Option Window')
        option_wnd.grab_set()
        option_wnd.grab_set()
        option_wnd.protocol("WM_DELETE_WINDOW", lambda w= option_wnd :option_closed(w))
        

我能想到的一個選項是像這樣綁定選項窗口:

option_wnd.bind('<Return>', lambda e: option_wnd.close()) # or withdraw() or quit() ?

將選項窗口綁定到按下 enter 時它會關閉(雖然我不知道上述功能的差異(有所以你應該查一下))但是如果你想使用Enter輸入值,這可能會妨礙(返回) 鍵,因為它會關閉窗口。 另一個選項是將選項窗口綁定到此事件:

option_wnd.bind('<FocusOut>', lambda e: option_wnd.close())

這是當窗口不再聚焦時,所以如果你按下回車鍵,它會打開一個新的,仍然打賭舊的應該關閉。 你也可以嘗試做一些邏輯編程,比如當 Enter 按下“打開”模式時,再次按下它不會打開窗口,當你關閉現有窗口時,它會再次允許。

def press_enter(event):
    #messagebox.showinfo("Inside")
    root.deiconify ()
    selected=trv.focus()
    print(trv.item(selected))
    print(str((event.keysym)))
    if str((event.keysym))=='Return':
        option_wnd=Toplevel(root)
        option_wnd.geometry('200x200')
        option_wnd.title('Option Window')
        option_wnd.grab_set()
        #option_wnd.pack()

暫無
暫無

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

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