tkinter จะรับค่าของวิดเจ็ต Entry ได้อย่างไร? [ทำซ้ำ]

ฉันกำลังพยายามเสนอความเป็นไปได้ให้ผู้ใช้คำนวณกำไรจากยอดขายที่คาดการณ์ไว้ หากมาร์จิ้นมีค่าที่แน่นอน (.23) ผู้ใช้ควรจะสามารถป้อนมูลค่าใดๆ ที่เป็นยอดขายที่คาดการณ์ไว้ได้:

from tkinter import *

root = Tk()

margin = 0.23
projectedSales = #value of entry
profit = margin * int(projectedSales)

#My function that is linked to the event of my button
def profit_calculator(event):
    print(profit)


#the structure of the window
label_pan = Label(root, text="Projected annual sales:")
label_profit = Label(root, text="Projected profit")
label_result = Label(root, text=(profit), fg="red")

entry = Entry(root)

button_calc = Button(root, text= "Calculate", command=profit_calculator)
button_calc.bind("<Button-1>", profit_calculator)

#position of the elements on the window
label_pan.grid(row=0)
entry.grid(row=0, column=1)
button_calc.grid(row=1)              
label_profit.grid(row=2)
label_result.grid(row=2, column=1)

root.mainloop()

person Pak    schedule 19.11.2017    source แหล่งที่มา
comment
คำถามเริ่มต้น ได้ รวมถึงวิธีใช้ข้อความรายการเป็นตัวแปรด้วย   -  person Nae    schedule 20.11.2017


คำตอบ (1)


คุณสามารถรับสิ่งที่อยู่ภายในวิดเจ็ตรายการได้โดยใช้วิธี get เช่น:

entry = tkinter.Entry(root)
entryString = entry.get()

นี่คือตัวอย่างที่ทำสิ่งที่คุณต้องการ:

import tkinter as tk

root = tk.Tk()

margin = 0.23

entry = tk.Entry(root)

entry.pack()

def profit_calculator():
    profit = margin * int(entry.get())
    print(profit)

button_calc = tk.Button(root, text="Calculate", command=profit_calculator)
button_calc.pack()

root.mainloop()

คุณอาจต้องการใช้ตัวเลือก textvariable และคลาส tkinter.IntVar() สำหรับการซิงโครไนซ์ข้อความจำนวนเต็มสำหรับวิดเจ็ตหลายตัว เช่น:

import tkinter as tk

root = tk.Tk()

margin = 0.23
projectedSales = tk.IntVar()
profit = tk.IntVar()

entry = tk.Entry(root, textvariable=projectedSales)

entry.pack()

def profit_calculator():
    profit.set(margin * projectedSales.get())

labelProSales = tk.Label(root, textvariable=projectedSales)
labelProSales.pack()

labelProfit = tk.Label(root, textvariable=profit)
labelProfit.pack()

button_calc = tk.Button(root, text="Calculate", command=profit_calculator)
button_calc.pack()

root.mainloop()

ตัวอย่างข้างต้นแสดงให้เห็นว่า labelProSales และ entry มีค่า text เท่ากันตลอดเวลา เนื่องจากทั้งคู่ใช้ตัวแปรเดียวกัน projectedSales เป็นตัวเลือก textvariable

person Nae    schedule 19.11.2017
comment
โอเค ขอบคุณมากสำหรับคำตอบ ฉันกำลังกระโดดไปหาคำตอบประเภทนี้ ฉันคิดว่าฉันเริ่มเข้าใจแล้ว! - person Pak; 20.11.2017
comment
ขออภัย แต่ที่นี่ระบุว่าเป็นข้อผิดพลาด: - person ; 29.08.2020
comment
@TroyD ข้อผิดพลาดนั้นไม่เกี่ยวข้องกับส่วนโค้ดด้านบนเนื่องจากตัวแปร inputS ไม่ กล่าวถึงเลย หากต้องการความช่วยเหลือเพิ่มเติมเกี่ยวกับข้อผิดพลาดดังกล่าว ฉันขอแนะนำให้อ่านใน ericlippert.com/2014/03/05/how-to-debug-small-programs - person Nae; 31.08.2020