The submit button in Python 3 seems to be malfunctioning. What steps can I take to fix this issue

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

class main_window(Frame):
    def __init__(self):
        tk.Frame.__init__(self)
        self.pack()
        self.master.title("MANAGEMENT")

        self.entry_button = Button(self, text="ENTRY", width=25, command=self.open_GUI)                        
        self.entry_button.grid(row=0, column=1, columnspan=2, sticky=W+E+N+S )

        self.show_bill_button = Button(self, text="SHOW BILL", width=25 )
        self.show_bill_button.grid(row=1, column=1, columnspan=2, sticky=W+E+N+S )

        self.members_button = Button(self, text="MEMBERS", width=25)                      
        self.members_button.grid(row=2, column=1, columnspan=2, sticky=W+E+N+S )

    def open_GUI(self):
        self.GUI = GUI()


class GUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        self.button_dict = {
            '1': 0,
            '2': 0,
            '3': 0,
            '4': 0
        }

        for key in self.button_dict:
            self.button_dict[key] = tk.IntVar()
            check_button = tk.Checkbutton(self, text=key,
                                            variable=self.button_dict[key])
            check_button.grid(sticky='w')

        submit_button = tk.Button(self, text="Submit",
                                        command=self.query_checkbuttons)
        submit_button.grid()

    def query_checkbuttons(self):
        for key, value in self.button_dict.items():
            state = value.get()
            if state != 0:
                print(key)
                self.button_dict[key].set(0)



def start(): 
    main_window().mainloop()

if __name__ == '__main__':
    start()

Answer №1

The issue you are facing is due to having two instances of Tk() running in your code. The first one is hidden inside the window1 function when you initialize the frame without a parent, and the second instance is in the GUI class. As you did not specify the parent of the IntVar, they are associated with the first created window instead of the intended one.

To address this problem, I made the following modifications to your code:

  • I changed the Window1 class to inherit from Tk since it serves as the main window
  • I updated your GUI class to inherit from Toplevel to prevent multiple instances of Tk
  • I explicitly specified the parent for the IntVar to remove any ambiguity

Below is the updated code:

import tkinter as tk

class Window1(tk.Tk):  
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("MANAGEMENT")

        self.button1 = tk.Button(self, text="ENTRY", width=25,command=self.GUI)                        
        self.button1.grid(row=0, column=1, columnspan=2, sticky="wesn" )

        self.button2 = tk.Button(self, text="SHOW BILL", width=25 )
        self.button2.grid(row=1, column=1, columnspan=2, sticky="wesn")

        self.button3 = tk.Button(self, text="MEMBERS", width=25)                      
        self.button3.grid(row=2, column=1 , columnspan=2, sticky="wesn")

    def GUI(self):
        self.GUI = GUI(self)


class GUI(tk.Toplevel):  
    def __init__(self, parent):
        tk.Toplevel.__init__(self, parent)

        self.buttonDic = {
            '1': 0,
            '2': 0,
            '3': 0,
            '4': 0
        }

        for key in self.buttonDic:
            self.buttonDic[key] = tk.IntVar(self)  
            aCheckButton = tk.Checkbutton(self, text=key,
                                          variable=self.buttonDic[key])
            aCheckButton.grid(sticky='')

        submitButton = tk.Button(self, text="Submit",
                                 command=self.query_checkbuttons)
        submitButton.grid()

    def query_checkbuttons(self):
        for key, value in self.buttonDic.items():
            state = value.get()
            if state != 0:
                print(key)
                self.buttonDic[key].set(0)


def main(): 
    Window1().mainloop()

if __name__ == '__main__':
    main()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Performing a Href link click using Selenium in PythonIn this tutorial,

What is the best way to interact with this element using Selenium in Python? <a onclick="ClearTrackingCode();" id="ctl00_phMainContent_CampaignGrid_grid_ctl02_btnSelect" title="Edit the selected campaigns" href="javascript:__doPostBack('ctl00$phMa ...

Creating a scatter plot with separate data points and exploring the method to use a colormap for colorizing the points

My aim with matplotlib is to create a scatter plot where both markers and colors vary. import matplotlib.pyplot as plt import numpy as np markers = np.array(["1","2","3","4","+",">"]) # Sample Data x = np.array([0, 2, 3, 4, 0, 1, 5, 6, 7, 8]) y = np.a ...

Is it possible to merge a dictionary with text file writing and then retrieve it as a dictionary once again?

I am making requests to a link and receiving JSON files as response. I am storing this data in a text file, but when I try to read it back, I want to interpret it as a dictionary. How can I achieve this? def url_sequence(limit=5): for i in range(limit ...

Error encountered in dataflow job initiated by CloudFunction: ModuleNotFoundError

Hey there, I'm encountering an issue while trying to create a dataflow job with CloudFunctions. All my CloudFunctions settings are in place. I'm fetching a scripting package (Python) from Google Storage. Within the .zip file, I have the followi ...

Using numbers such as 1, 2, 3 in Python to execute various sections of code - a guide

Just starting out on stack overflow and diving into Python with version 3.8.2. Currently experimenting with coding on . Working on a math solver that uses specific formulas, including print functions, input functions, and integer variables. The goal is t ...

An HTTPError occurred while using the Bing REST API, with the given request details and response code, message, headers, and

Is there a way to retrieve latitude and longitude locations for a large number of addresses without getting blocked by services like Bing? I have around 100k+ addresses that I need to process, but it seems like my current code is causing me to be flagged ...

How can you handle special characters in a password when using Psycopg2?

I'm facing a challenge connecting to a database instance because my password contains special characters like backslash, plus, dot, asterisk/star, and at symbol. An example of such a password is 12@34\56.78*90 (isn't regex a nightmare?). Wh ...

Opening a Webpage with Logged-in Status Using Python and Selenium

I've seen similar questions asked about this topic, but I have checked numerous posts and still can't figure it out. My goal is to launch a webpage using my existing Chrome profile/user data so that I don't have to log in again. Ideally, I w ...

Transfer information from python-cgi to AJAX

Currently, I am in the process of creating a UI version of the find command found in Linux. In this implementation, I receive the location and filename parameters for the find command through a CGI form that has been built using Python. When the user submi ...

Encountering an issue when attempting to save two forms within a single template in

Currently, I am working on a view that contains 2 separate forms. These forms do not share any related fields. Form 1: Includes a FilteredSelectMultiple widget displaying files available for download from an FTP server. Each file in this form meets certai ...

converting web job json data into a pandas dataframe

Currently, I am endeavoring to retrieve JSON data for logs from Azure WebJobs services using the REST API. While I have managed to extract the data into a dataframe with various columns, my goal is to format the "lastrun" column in a tabular layout, where ...

Getting the h1 text from a div class using scrapy or selenium

I am working with Python using Scrapy and Selenium. My goal is to extract the text from the h1 tag that is within a div class. For instance: <div class = "example"> <h1> This is an example </h1> </div> Here is my implementat ...

Do not include undesired tags when using Beautifulsoup in Python

<span> I Enjoy <span class='not needed'> slapping </span> your back </span> How can "I Enjoy your back" be displayed instead of "I Enjoy slapping your back" This is what I attempted: result = soup.find_all(&apos ...

Transforming data in Pandas by consolidating multiple columns into a single column

I have some data that needs to be reshaped to better organize the results. The data consists of initial columns followed by a varying number of columns grouping the data. Each group is marked with an 'x' if the key belongs to it, with keys potent ...

The error message "TypeError: 'bool' object is not iterable while attempting to use all()" is indicating that a boolean

I wrote a code to determine if a list is monotonically increasing or decreasing. However, I encountered the following error message: TypeError Traceback (most recent call last) <ipython-input-64-63c9df4c ...

Gather information about users from the LinkedIn r_basicprofile API

Successfully implemented LinkedIn sign in using Python, but facing an issue with retrieving additional fields beyond 'r_liteProfile'. Attempted to access 'r_basicProfile' to retrieve the necessary data. The code snippet used is as foll ...

Is it possible to include a hyphen (-) in a query parameter name when using FastAPI?

Let's explore a sample application: from typing import Annotated import uvicorn from fastapi import FastAPI, Query, Depends from pydantic import BaseModel app = FastAPI() class Input(BaseModel): a: Annotated[str, Query(..., alias="your_na ...

What is the best way to identify the state in my gridworld-style environment?

The issue I am attempting to address is more complex than it appears. To simplify the problem, I have created a simple game that serves as a precursor to solving the larger problem. Starting with a 5x5 matrix where all values are initially set to 0: stru ...

What is the purpose of using namespaces for static methods in Python?

class B(object): def __init__(self, number): self.number = B.add_one(number) @staticmethod def add_one(number): return number + 1 We can create a static method inside a class and use it anywhere. But why do we need to prefix t ...

What occurs when a python mock is set to have both a return value and a series of side effects simultaneously?

I'm struggling to comprehend the behavior of some test code. It appears as follows: import pytest from unittest.mock import MagicMock from my_module import MyClass confusing_mock = MagicMock( return_value=b"", side_effect=[ Connectio ...