【发布时间】:2019-04-22 18:37:18
【问题描述】:
我正在尝试使用 tkinter 编写 Python 3 代码,以根据输入的数据生成体积计算。
目前,我的代码有效,但我想做的是当通过单选按钮选择矩形棱镜时,让球体的小部件消失,反之亦然,以便只显示相关项目。
我找到了一些想法,但在我当前的设置中实施它们时遇到了困难。如果有人可以提供帮助,我将不胜感激。
代码:
from tkinter import *
from tkinter import messagebox
from volumes import * #basic volume calculations
import sys
def calculate(): #assigns vars, calls volumes module
x = option.get()
if x == 1:
heightx = heighttxt.get()
widthx = widthtxt.get()
lengthx = lengthtxt.get()
height = float(heightx)
width = float(widthx)
length = float(lengthx)
volume= rp_volume(length, width, height)
messagebox.showinfo('You selected Rectangular Prism', volume) #displays calculation result
if x == 2:
radx = radtxt.get()
radius = float(radx)
volume = sp_volume(radius)
messagebox.showinfo('You selected Sphere', volume) #displays calculation result
window = Tk() #creates window ident
window.title("Volume Calculator")
window.geometry('450x300')
option = IntVar()
option.set(1)
Radiobutton(window, text="Rectangular Prism", variable=option, value=1).grid(column=1, row=1)
Radiobutton(window, text="Sphere", variable=option, value=2).grid(column=2, row=1)
heightlbl = Label(window, text="Enter the height: ", padx=5, pady=5) #creates ident labels
widthlbl = Label(window, text="Enter the width: ", padx=5, pady=5)
lengthlbl = Label(window, text="Enter the length: ", padx=5, pady=5)
radlbl = Label(window, text ="Or enter the radius of a sphere: ", padx=5, pady=5)
heighttxt = Entry(window,width=10) #creates entry boxes
widthtxt = Entry(window,width=10)
lengthtxt = Entry(window,width=10)
radtxt = Entry(window, width=10)
calcbtn = Button(window, text="Calculate the volume", command=calculate, padx=5, pady=5) #hey it's a button that calls the calculate function!
quitbtn = Button(window, text="Quit", command=window.destroy) #quit button does what it says on the tin
heightlbl.grid(column=1, row=3) #assigns grid positions (preferred to pack for precise layout)
widthlbl.grid(column=1, row=4)
lengthlbl.grid(column=1, row=5)
radlbl.grid(column=1, row=6)
heighttxt.grid(column=2, row=3)
widthtxt.grid(column=2, row=4)
lengthtxt.grid(column=2, row=5)
radtxt.grid(column=2, row=6)
calcbtn.grid(column=2, row=7)
quitbtn.grid(column=2, row=8)
window.mainloop() #closes window mainloop
【问题讨论】: