如何使用组合框(Tkinter)?

问题描述 投票:0回答:1

我目前正在从事一个使用 Tkinter 作为 GUI 框架的零售管理系统项目。该系统的界面设计为使用图像作为背景,按钮放置在特定区域的图像上。

我已经设法显示按钮和输入框,但我无法让组合框显示在界面上。

这是我的主程序的输出:Click link

我的代码:

#BBCVZJS0
from tkinter import *
from tkinter.ttk import Combobox
import tkinter as tk
import sqlite3
import tkinter.messagebox as messagebox

def main_window():
        # create a new window
    invoice = Toplevel()
    # load the image file
    billimage1 = PhotoImage(file="C:/Users/hasee/OneDrive/Documents/CODE/billimage.PNG")
    # create a label widget and set it as the background of the window
    label2 = Label(invoice, image = billimage1)
    label2.pack()
    
    def search_bill():
            # Connect to the database
        conn = sqlite3.connect('store.db')
        c = conn.cursor()

        # Get the value of the bill entry box
        bill_no = bill_entry.get()

        # Execute a query to fetch the bill number from the database
        c.execute("SELECT bill_no FROM bill WHERE bill_no = ?", (bill_no,))
        result = c.fetchone()

        # Check if the result is not None
        if result is not None:
        # Execute a query to fetch the product information from the inventory table
            c.execute("SELECT product_name, price, quantity FROM raw_inventory WHERE product_name = 'Big G Cereals Cinnamon Toast Crunch' AND price = 12 AND quantity = 10")
            product_info = c.fetchone()

            # Execute a query to fetch the customer information from the bill table
            c.execute("SELECT customer_name, customer_no FROM bill WHERE customer_name = 'Adam Fawn' AND customer_no = '02086132851'")
            customer_info = c.fetchone()

            # Close the database connection
            conn.close()

            # Check if both the product and customer information are not None
            if product_info is not None and customer_info is not None:
                # Create labels to display the product and customer information
                product_label = tk.Label(invoice, text=f"{product_info[0]}{' ' * 45}{product_info[1]}{' ' * 83}£{product_info[2]}", font=("Arial", 13), bg="white")
                customer_label = tk.Label(invoice, text=f"{customer_info[0]}{' ' * 109}Phone Number:  {customer_info[1]}", font=("Arial", 13), bg="white")
                bill_label = tk.Label(invoice, text=f"{bill_no}", font=("Arial", 13), bg="white")
                total_label = tk.Label(invoice, text=f"Total: £{product_info[2]}", font=("Arial", 15), bg="white", fg = "red")

                # Place the labels on the GUI
                product_label.place(relx=0.44, rely=0.6)
                customer_label.place(relx=0.52, rely=0.458)
                bill_label.place(relx=0.5, rely=0.483)
                total_label.place(relx = 0.44, rely =0.65)

        else:
            # Close the database connection
            conn.close()

            # Show a message box to indicate that the search was unsuccessful
            messagebox.showwarning("Search Result", "Bill number does not exist in the database")
            
    def generate_bill():
        conn = sqlite3.connect('store.db')
        c = conn.cursor()

        # Get the values from the entry boxes
        cust_name2 = cust_name.get()
        contact_num2 = contact_num.get()

        c.execute("SELECT customer_name FROM bill WHERE customer_name = 'Adam Fawn'")
        customer_check = c.fetchone()

        c.execute("SELECT customer_no FROM bill WHERE customer_no = '02086132851'")
        phone_check = c.fetchone()

        # Check if the customer name and contact number are not empty
        if cust_name2 and contact_num2:
            # Check if the customer name and contact number match the values in the database
            if cust_name2 == customer_check[0] and contact_num2 == phone_check[0]:
                # Get the bill from the search_bill function
                
                conn = sqlite3.connect('store.db')
                c = conn.cursor()
                
                bill_no = bill_entry.get()

                # Execute a query to fetch the bill number from the database
                c.execute("SELECT bill_no FROM bill WHERE bill_no = ?", (bill_no,))
                result = c.fetchone()
                
                c.execute("SELECT product_name, price, quantity FROM raw_inventory WHERE product_name = 'Big G Cereals Cinnamon Toast Crunch' AND price = 12 AND quantity = 10")
                product_info = c.fetchone()

                # Execute a query to fetch the customer information from the bill table
                c.execute("SELECT customer_name, customer_no FROM bill WHERE customer_name = 'Adam Fawn' AND customer_no = '02086132851'")
                customer_info = c.fetchone()

                # Close the database connection
                conn.close()
                
                product_label = tk.Label(invoice, text=f"{product_info[0]}{' ' * 45}{product_info[1]}{' ' * 83}£{product_info[2]}", font=("Arial", 13), bg="white")
                customer_label = tk.Label(invoice, text=f"{customer_info[0]}{' ' * 109}Phone Number:  {customer_info[1]}", font=("Arial", 13), bg="white")
                bill_label = tk.Label(invoice, text=f"{bill_no}", font=("Arial", 13), bg="white")
                total_label = tk.Label(invoice, text=f"Total: £{product_info[2]}", font=("Arial", 15), bg="white", fg = "red")

                # Place the labels on the GUI
                product_label.place(relx=0.44, rely=0.6)
                customer_label.place(relx=0.52, rely=0.458)
                bill_label.place(relx=0.5, rely=0.483)
                total_label.place(relx = 0.44, rely =0.65)

                # Display a message to the user that the bill is generated
                messagebox.showinfo("Bill Generated", "The bill has been generated.")
            else:
                # Display an error message to the user that the customer name and contact number do not match
                messagebox.showerror("Error", "The customer name or contact number is incorrect.")
        else:
            # Display an error message to the user that they need to enter values
            messagebox.showerror("Error", "Please enter a customer name and contact number.")
            
    def clear_bill():
        invoice.destroy()
        main_window()
        
    def dropdown():
        # create a Combobox widget with items from the 'items' list
        combo = Combobox(invoice, values=items)
        # set the default value to the first item in the list
        combo.current(0)
        items = ['Item 1', 'Item 2', 'Item 3']
        combo.pack()

        # set up the variables
        
        

    
    
    logout_img = tk.PhotoImage(file="C:/Users/hasee/OneDrive/Documents/CODE/logout.PNG")
    logout_button = tk.Button(invoice, image=logout_img, command="", borderwidth=0, bg='white')
    logout_button.place(relx=0.025, rely=0.099)
    
    search_img = tk.PhotoImage(file="C:/Users/hasee/OneDrive/Documents/CODE/search.PNG")
    search_button = tk.Button(invoice, image=search_img, command = search_bill, borderwidth=0, bg='white')
    search_button.place(relx=0.3, rely=0.22)
    
    cart_img = tk.PhotoImage(file="C:/Users/hasee/OneDrive/Documents/CODE/cart.PNG")
    cart_button = tk.Button(invoice, image=cart_img, command="", borderwidth=0, bg='white')
    cart_button.place(relx=0.085, rely=0.725)
    
    remove_img = tk.PhotoImage(file="C:/Users/hasee/OneDrive/Documents/CODE/remove.PNG")
    remove_button = tk.Button(invoice, image=remove_img, command="", borderwidth=0, bg='white')
    remove_button.place(relx=0.176, rely=0.722)
    
    clear_img = tk.PhotoImage(file="C:/Users/hasee/OneDrive/Documents/CODE/clear.PNG")
    clear_button = tk.Button(invoice, image=clear_img, command=clear_bill, borderwidth=0, bg='white')
    clear_button.place(relx=0.265, rely=0.72)
    
    clear_img2 = tk.PhotoImage(file="C:/Users/hasee/OneDrive/Documents/CODE/clear.PNG")
    clear_button2 = tk.Button(invoice, image=clear_img2, command="", borderwidth=0, bg='white')
    clear_button2.place(relx=0.22, rely=0.871)
    
    total_img = tk.PhotoImage(file="C:/Users/hasee/OneDrive/Documents/CODE/total.PNG")
    total_button = tk.Button(invoice, image=total_img, command="", borderwidth=0, bg='white')
    total_button.place(relx=0.04, rely=0.878)
    
    generate_img = tk.PhotoImage(file="C:/Users/hasee/OneDrive/Documents/CODE/generate.PNG")
    generate_button = tk.Button(invoice, image=generate_img, command=generate_bill, borderwidth=0, bg='white')
    generate_button.place(relx=0.13, rely=0.875)
    
    exit_img = tk.PhotoImage(file="C:/Users/hasee/OneDrive/Documents/CODE/exit.PNG")
    exit_button = tk.Button(invoice, image=exit_img, command="", borderwidth=0, bg='white')
    exit_button.place(relx=0.31, rely=0.8715)
    
    bill_entry = tk.Entry(invoice, width=20, font=("Arial", 20), bd = 0) # create an textbox for the phone number
    bill_entry.place(relx=0.105, rely=0.235)
    
    cust_name = tk.Entry(invoice, width=20, font=("Arial", 20), bd = 0) # create an textbox for the phone number
    cust_name.place(relx=0.515, rely=0.235)
    
    contact_num = tk.Entry(invoice, width=20, font=("Arial", 20), bd = 0) # create an textbox for the phone number
    contact_num.place(relx=0.795, rely=0.235)
    
    
    invoice.mainloop()
                        
main_window()


组合框的编写代码:

def dropdown():
        # create a Combobox widget with items from the 'items' list
        combo = Combobox(invoice, values=items)
        # set the default value to the first item in the list
        combo.current(0)
        items = ['Item 1', 'Item 2', 'Item 3']
        combo.pack()

目前,就我正在处理的列表中的项目而言,我的 dropdown() 函数非常简单。但是,我遇到了组合框未显示在 GUI 上的问题。我已经尝试使用 place() 方法来查看它是否可以解决问题,但不幸的是它没有。

我也试过自己运行combobox函数,也成功显示了。但是,当我将它与我的其余代码集成时,组合框没有出现。我开始怀疑我用作背景的图像可能存在问题。你对我如何解决这个问题有什么想法或建议吗?

python function tkinter combobox ttk
1个回答
0
投票

您需要使用 StringVar 或 IntVar 甚至 FloatVar 来使用回调函数从 Combobox 中获取值。 Varaible 应该用 "varaible".trace('w', "callback_function_name"

试试这个:

combo_output_var = StringVar()  # output variabel for the combobox -> callback function with trace should be used!
combobox_list = Combobox(invoice, textvariable= combo_output_var)  # Create the combobox
combobox_list['values'] = items  # Give the Combobox all the selectable values
combobox_list['state']  = 'readonly  # The state from the combobox could be set... ('readonly' is mostly used) 
combobox_list.current(index_items)  # Set the default visible value 
combobox.pack()  # Pack the combobox
© www.soinside.com 2019 - 2024. All rights reserved.