简体   繁体   English

使用 tkinter 的 Python GUI 编程

[英]Python GUI programing using tkinter

I have a form which is having multiple rows.我有一个包含多行的表单。 By pressing enter it opens up a option window.按回车键会打开一个选项窗口。 But every time i hit enter it opens a new option window.但是每次我按回车键都会打开一个新的选项窗口。 How can i control and check if an option window is open then don't open an option window.我如何控制和检查选项窗口是否打开然后不打开选项窗口。

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()

Everytime I hit enter on the root window it opens a pop up window.每次我在根窗口上按 Enter 键时,它都会打开一个弹出窗口。 I need to control the it.我需要控制它。 if the pop up window is open then we should not allow another pop up to open.如果弹出窗口是打开的,那么我们不应该允许另一个弹出窗口打开。 在此处输入图片说明

The direct way is to use winfo_exists() :直接的方法是使用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)
            .....

But I don't think you need to create this window each time when user type Enter .Create it at the beginning, just show it when user type Enter但是我不认为每次用户键入Enter时都需要创建此窗口。在开始时创建它,只需在用户键入Enter时显示它

For example:例如:

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.

If you do not uses classes you could do the following:如果您不使用类,您可以执行以下操作:

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))
        

one option I can think of is binding the option window like this:我能想到的一个选项是像这样绑定选项窗口:

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

binding the option window to when enter is pressed it gets closed (althought I dont know about differences of above functions(there are so you should look up that)) but this can get in the way if you want to enter values using Enter (Return) key because it will close the window.将选项窗口绑定到按下 enter 时它会关闭(虽然我不知道上述功能的差异(有所以你应该查一下))但是如果你想使用Enter输入值,这可能会妨碍(返回) 键,因为它会关闭窗口。 The other option is to bind option window to this event:另一个选项是将选项窗口绑定到此事件:

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

which is when window is not focused on anymore so if you pressed enter it would open a new one still bet the old one should be closed.这是当窗口不再聚焦时,所以如果你按下回车键,它会打开一个新的,仍然打赌旧的应该关闭。 Also you can try doing some logic programming with sth like when enter is presses 'turn on' a mode when pressing it again wont open window and when you close the existing window it will again allow that.你也可以尝试做一些逻辑编程,比如当 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