ttk tkinter multiple frames/windows

2024/5/20 5:12:08

The following application I have created is used to demonstrate multiple windows in tkinter. The main problem is that none of the Entry controls, neither in the bmi-calculator or the converter, accept the values in the entry boxes - they get a ValueError when I do a calculation.

from tkinter import *
from tkinter import ttk
from tkinter import messageboxclass App1(ttk.Frame):def createWidgets(self):#text variablesself.i_height = StringVar()self.i_weight = StringVar()self.o_bmi = StringVar()#labelsself.label1 = ttk.Label(self, text="Enter your weight:").grid(row=0, column=0, sticky=W)self.label2 = ttk.Label(self, text="Enter your height:").grid(row=1, column=0, sticky=W)self.label3 = ttk.Label(self, text="Your BMI is:").grid(row=2, column=0, sticky=W)#text boxesself.textbox1 = ttk.Entry(self, textvariable=self.i_weight).grid(row=0, column=1, sticky=E)self.textbox2 = ttk.Entry(self, textvariable=self.i_height).grid(row=1, column=1, sticky=E)self.textbox3 = ttk.Entry(self, textvariable=self.o_bmi).grid(row=2, column=1, sticky=E)#buttonsself.button1 = ttk.Button(self, text="Cancel/Quit", command=self.quit).grid(row=3, column=1, sticky=E)self.button1 = ttk.Button(self, text="Ok", command=self.calculateBmi).grid(row=3, column=2, sticky=E)def calculateBmi(self):try:self.weight = float(self.i_weight.get())self.height = float(self.i_height.get())self.bmi = self.weight / self.height ** 2.0self.o_bmi.set(self.bmi)except ValueError:messagebox.showinfo("Error", "You can only use numbers.")finally:self.i_weight.set("")self.i_height.set("")def __init__(self, master=None):ttk.Frame.__init__(self, master)self.grid()self.createWidgets()class App2(ttk.Frame):def create_widgets(self):"""Create the widgets for the GUI"""#1 textbox (stringvar)self.entry= StringVar()self.textBox1= ttk.Entry(self, textvariable=self.entry).grid(row=0, column=1)#5 labels (3 static, 1 stringvar)self.displayLabel1 = ttk.Label(self, text="feet").grid(row=0, column=2, sticky=W)self.displayLabel2 = ttk.Label(self, text="is equivalent to:").grid(row=1, column=0)self.result= StringVar()self.displayLabel3 = ttk.Label(self, textvariable=self.result).grid(row=1, column=1)self.displayLabel4 = ttk.Label(self, text="meters").grid(row=1, column=2, sticky=W)#2 buttonsself.quitButton = ttk.Button(self, text="Quit", command=self.quit).grid(row=2, column=1, sticky=(S,E))self.calculateButton = ttk.Button(self, text="Calculate", command=self.convert_feet_to_meters).grid(row=2, column=2, sticky=(S,E))def convert_feet_to_meters(self):"""Converts feet to meters, uses string vars and converts them to floats"""self.measurement = float(self.entry.get())self.meters = self.measurement * 0.3048self.result.set(self.meters)def __init__(self, master=None):ttk.Frame.__init__(self, master)self.grid()self.create_widgets()def button1_click():root = Tk()app = App1(master=root)app.mainloop()def button2_click():root = Tk()app = App2(master=root)app.mainloop()def main():window = Tk()button1 = ttk.Button(window, text="bmi calc", command=button1_click).grid(row=0, column=1)button2 = ttk.Button(window, text="feet conv", command=button2_click).grid(row=1, column=1)window.mainloop()if __name__ == '__main__':main()

How can I fix this, but still maintaining the class structure and the use of python3? BTW - Anything similar to C#'s form1.Show()?

Answer

You have to convert the StringVar() to an integer/float or use IntVar() or DoubleVar()

There are other problems as well. Statements like the following return "None" since it is a grid() object and not a Label() object:

self.label1 = ttk.Label(self, text="Enter your weight:").grid(row=0, column=0, sticky=W)   

I think you will also have problems with two Tk() windows open at the same time. Use Toplevel() or separate frames instead.

https://en.xdnf.cn/q/72675.html

Related Q&A

input() vs sys.stdin.read()

import sys s1 = input() s2 = sys.stdin.read(1)#type "s" for examples1 == "s" #False s2 == "s" #TrueWhy? How can I make input() to work properly? I tried to encode/decode…

Renormalize weight matrix using TensorFlow

Id like to add a max norm constraint to several of the weight matrices in my TensorFlow graph, ala Torchs renorm method.If the L2 norm of any neurons weight matrix exceeds max_norm, Id like to scale it…

Numpy: find the euclidean distance between two 3-D arrays

Given, two 3-D arrays of dimensions (2,2,2):A = [[[ 0, 0],[92, 92]],[[ 0, 92],[ 0, 92]]]B = [[[ 0, 0],[92, 0]],[[ 0, 92],[92, 92]]]How do you find the Euclidean distance for each vector in A and B e…

Is it possible to break from lambda when the expected result is found

I am Python newbie, and just become very interested in Lambda expression. The problem I have is to find one and only one target element from a list of elements with lambda filter. In theory, when the t…

Intersection of multiple pandas dataframes

I have a number of dataframes (100) in a list as:frameList = [df1,df2,..,df100]Each dataframe has the two columns DateTime, Temperature.I want to intersect all the dataframes on the common DateTime col…

docker with pycharm 5

I try to build a docker-based development box for our django app. Its running smoothly.None of my teammembers will care about that until there is a nice IDE integration, therefore I play the new and sh…

How to make a simple Python REST server and client?

Im attempting to make the simplest possible REST API server and client, with both the server and client being written in Python and running on the same computer.From this tutorial:https://blog.miguelgr…

Histogram fitting with python

Ive been surfing but havent found the correct method to do the following.I have a histogram done with matplotlib:hist, bins, patches = plt.hist(distance, bins=100, normed=True)From the plot, I can see …

Subtract each row of matrix A from every row of matrix B without loops

Given two arrays, A (shape: M X C) and B (shape: N X C), is there a way to subtract each row of A from each row of B without using loops? The final output would be of shape (M N X C).Example A = np.ar…

Programmatically setting access control limits in mosquitto

I am working on an application that will use mqtt. I will be using the python library. I have been leaning towards using mosquitto but can find no way of programmatically setting access control limits …