[英]printing a selected value from a combobox into a textbox
我有一個包含 50+ 幀的 Python 文件。 每個框架有 5 個單選按鈕和 1 個文本框。 每個單選按鈕都有一個預先確定的數值,將打印到文本框。
我想做的是用 combobox 替換單選按鈕。 combobox 設置有一個帶有數學方程的基本數值。
該原理有效,但我只能將其打印到 shell。
在過去的幾個月里,我從帖子中嘗試了許多不同的代碼。
我認為社區可能會幫助我。
我附上了我的代碼片段。
from tkinter import *
from tkinter import Tk
import tkinter as tk
from tkinter import ttk
from tkinter.ttk import Combobox
root=tk.Tk()
root.title("Dental Milling Machines")
root.geometry("250x200")
def onclick1():
textbox1.delete('1.0', 'end')
textbox1.insert('end', '2.83')
def onclick2():
textbox1.delete('1.0', 'end')
textbox1.insert('end', '5.66')
def Cnum():
print(combobox1.current()*2.83)
cb_var1 = tk.IntVar()
frame1 = Frame(root, height = 150, width= 150, relief= RAISED, bd=8, bg="blue")
frame1.grid(row=0, column=0, pady=2,sticky="NW")
label = Label(frame1, text="Frame 1", fg="red")
label.grid(row=0, columnspan=3, pady= 1, sticky= "W")
button1=Radiobutton(frame1, text="Submit", command=Cnum)
button1.grid(row=1, column=1, pady= 1, padx= 5, sticky= "W")
textbox1=Text(frame1, borderwidth=1, wrap="none", width=5, height=1)
textbox1.grid(row=0, column=1,padx=10, sticky="W")
combobox1=Combobox(frame1, width=7)
combobox1.grid(row=1, column=0)
combobox1['values'] = ( '', ' 1', ' 2', ' 3', ' 4', ' 5')
button1=Radiobutton(frame1, text="1 Unit ", variable=cb_var1, command=onclick1)
button1.grid(row=2, column=0, pady= 1, padx= 5, sticky= "W")
button2=Radiobutton(frame1, text="2 Unit ", variable=cb_var1, command=onclick2)
button2.grid(row=4, column=0, pady= 1, padx= 5, sticky= "W")
root.mainloop()
這會將 2.83 的結果乘以從 combobox 中選擇的值到 textbox1 中。
def Cnum():
textbox1.insert(tk.END, combobox1.current() * 2.83)
如果您希望在 combobox 中選擇值時更新文本框中的值,我們可以將其 ComboboxSelected 事件綁定到 Cnum。
為此,我們需要更改代碼中的一些內容。
首先我們需要添加代碼來綁定事件,
combobox1=Combobox(frame1, width=7)
combobox1.grid(row=1, column=0)
combobox1['values'] = ( '', ' 1', ' 2', ' 3', ' 4', ' 5')
# bind ComboboxSelected event to Cnum
combobox1.bind('<<ComboboxSelected>>', Cnum)
我們需要更改 Cnum function 以獲取事件參數。
def Cnum(event):
textbox1.delete('1.0', 'end')
textbox1.insert("1.0", combobox1.current() * 2.83)
現在要設置/更改文本框中的值,您需要做的就是 select combobox 中的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.