我正在尝试使用tkinter编写Python 3代码,以根据输入的数据生成体积计算。
当前,我的代码有效,但是我想做的是,当通过单选按钮选择矩形棱柱时,球形小部件消失了,反之亦然,所以只显示了相关的项目。
我找到了一些想法,但是在当前设置中很难实现它们。如果有人可以提供帮助,我将非常感谢。
代码:
//here it is where I would like to do the above mentioned check
答案 0 :(得分:0)
要实现此目的,您可以将长方体和球体所需的小部件放在不同的框架中,并将命令参数添加到单选按钮中,单选按钮被选中时将显示相应的框架,而grid_forget
将显示另一个框架。这是代码。 (请注意,我对此 volumes 模块一无所知,因此您可以相应地对其进行更改)
from tkinter import *
from tkinter import messagebox
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 = length*width*height
messagebox.showinfo('You selected Rectangular Prism', volume) #displays calculation result
if x == 2:
radx = radtxt.get()
radius = float(radx)
volume = 4/3*3.14*radius**3
messagebox.showinfo('You selected Sphere', volume) #displays calculation result
def recprism():
sphere_frame.grid_forget()
rec_frame.grid(row=1, column=0)
def sphere():
rec_frame.grid_forget()
sphere_frame.grid(row=1, column=0)
window = Tk() #creates window ident
window.title("Volume Calculator")
window.geometry('450x300')
option = IntVar()
Radiobutton(window, text="Rectangular Prism", variable=option, value=1, command=recprism).grid(column=0, row=0)
Radiobutton(window, text="Sphere", variable=option, value=2, command=sphere).grid(column=1, row=0)
rec_frame = Frame(window)
sphere_frame = Frame(window)
heightlbl = Label(rec_frame, text="Enter the height: ", padx=5, pady=5) #creates ident labels
widthlbl = Label(rec_frame, text="Enter the width: ", padx=5, pady=5)
lengthlbl = Label(rec_frame, text="Enter the length: ", padx=5, pady=5)
radlbl = Label(sphere_frame, text ="Enter the radius of a sphere: ", padx=5, pady=5)
heighttxt = Entry(rec_frame, width=10) #creates entry boxes
widthtxt = Entry(rec_frame, width=10)
lengthtxt = Entry(rec_frame, width=10)
radtxt = Entry(sphere_frame, 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=0, row=0) #assigns grid positions (preferred to pack for precise layout)
widthlbl.grid(column=0, row=1)
lengthlbl.grid(column=0, row=2)
radlbl.grid(column=0, row=0)
heighttxt.grid(column=1, row=0)
widthtxt.grid(column=1, row=1)
lengthtxt.grid(column=1, row=2)
radtxt.grid(column=1, row=0)
calcbtn.grid(column=1, row=1)
quitbtn.grid(column=1, row=2)
window.mainloop()