簡體   English   中英

將變量傳遞給 Python、tkinter 中的另一個變量

[英]Pass variable onto another variable in Python, tkinter

我想傳遞水果的價值,這樣我就可以將其打印出來,因為如果選擇了蘋果,則您的your fruit is apple是蘋果,而如果同時選擇了水果, your fruit is apple orange 也許我應該使用數組?

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

app = tk.Tk()

def show():
    fruit=""
    if apple.get()==1:
        fruit = "apple"
    if orange.get()==1:
        fruit = "orange"
    
    msg = "your fruit is %s"%fruit
    print(msg)

Label(app, text="fruit selected").grid(row=4,column=0, sticky=W)
apple = IntVar()
Checkbutton(app, text="apple", variable=apple,command = show).grid(row=4,column=1, sticky=W)
orange = IntVar()
Checkbutton(app, text="orange", variable=orange).grid(row=4,column=2, sticky=W)


#size
app.title('Basic message')
app.geometry("700x500")

app.mainloop()

可以有很多方法可以做到這一點,但讓我們首先在您的示例中進行。 只需添加一行並對您的show進行一些改進 function 就會給您帶來想要的結果。

def show():
    fruit=""
    if apple.get() and orange.get():
        fruit = 'apple orange' 
    elif apple.get():
        fruit = "apple"
    elif orange.get():
        fruit = "orange"

    msg = "your fruit is %s"%fruit
    print(msg)

但是整個代碼可以改進,使用 for 循環創建不同的水果Checkbutton s 並將它們的變量IntVar保存為實例中的var這將方便以后訪問,最后將這些 Checkbuttons 保存在列表中以在show function 中訪問它們. 邏輯很簡單,我只是檢查勾選了哪個復選按鈕並將它們的文本添加到fruit變量中。

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

app = tk.Tk()
ckb_list = []

def show():
    f = ''
    for ckb in ckb_list:
        if ckb.var.get():
            f += ckb['text'] + ' '
    msg = "your fruit is %s"%f
    print(msg)

Label(app, text="fruit selected").grid(row=4,column=0, sticky=W)

for col, fruit in enumerate(('apple', 'orange', 'banana', 'mango')):
    ckb = Checkbutton(app, text=fruit, command=show)
    ckb.var = ckb['variable'] = IntVar()
    ckb.grid(row=4,column=col+1, sticky=W)
    ckb_list.append(ckb)

#size
app.title('Basic message')
app.geometry("700x500")

app.mainloop()

您忘記添加 command=show in orange 復選框。 如果一個或多個復選框被選中,則只打印一條消息也是很好的。

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

app = tk.Tk()

def show():
    fruit=""
    if apple.get()==1:
        fruit = "apple"
    if orange.get()==1:
        fruit = "orange"
    
    if orange.get()==1 or apple.get()==1:
        msg = "your fruit is %s"%fruit
        print(msg)

Label(app, text="fruit selected").grid(row=4,column=0, sticky=W)
apple = IntVar()
Checkbutton(app, text="apple", variable=apple,command = show).grid(row=4,column=1, sticky=W)
orange = IntVar()
Checkbutton(app, text="orange", variable=orange, command = show).grid(row=4,column=2, sticky=W)


#size
app.title('Basic message')
app.geometry("700x500")

app.mainloop()

如果您想添加更多框,我還建議使用數組或列表。 您還可以考慮使用 class 來更好地“變量管理”

暫無
暫無

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

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