21839

Adding or deleting tkinter widgets from within other modules

Question:

I'd like to know how I can add or delete widgets from within an imported module. I fail to access them correctly. I know, using OOP would make it easier, but I tried to grasp OOP and while the principles are easy I can't get my head around the details, so since I lack a proper teacher, I need a procedural solution.

This is the main script:

#!/usr/bin/python try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk import os import sys sys.path.append(os.path.dirname(os.path.realpath(__file__))) import target def myfunction(event): canvas.configure(scrollregion=canvas.bbox("all"),width=300,height=200) def test(): target.secondWindow() root = tk.Tk() root.geometry("600x350+30+50") myframe = tk.Frame(root,relief="groove",bd=1) myframe.place(x=20, y=30, width=560, height=200 ) canvas = tk.Canvas(myframe) frame = tk.Frame(canvas) myscrollbar=tk.Scrollbar(myframe, orient="vertical", command=canvas.yview) canvas.configure(yscrollcommand=myscrollbar.set) myscrollbar.pack(side="right", fill="y") canvas.pack(side="left") canvas.create_window((0,0), window=frame, anchor='nw') allMissions = { "1":{"name":"go"}, "2":{"name":"see"}, "3":{"name":"win"}, "4":{"name":"party"}} # this would be a text file for a in allMissions.keys(): mn = allMissions[a]["name"] tk.Label(frame, text=mn, justify="left").grid(row=int(a), column=0) # what's bind really doing? frame.bind("<Configure>", myfunction) test = tk.Button(root, command=test, text="TEST") test.place(x = 20, y = 250, width=580, height=40) tk.mainloop()

<strong>and this is the imported module: target.py</strong>

try: # Python2 import Tkinter as tk except ImportError: # Python3 import tkinter as tk def changeMainWindow(): # here's where I'm stuck print("What do I have to do to add a new") print("label in the main window from here?") print("Or to delete it?") def secondWindow(): amWin = tk.Toplevel() amWin.geometry("300x200+720+50") button = tk.Button(amWin, text="OK", command=changeMainWindow) button.place(x = 20, y = 80, width=260, height=30) #amWin.mainloop() comment noticed (:

Answer1:

You do it by passing the memory address of whatever widget to the second program. There is no reason to import Tkinter again as you can just pass a pointer to the existing instance. If you are going to be doing anything more than simple experimenting with Tkinter, then it is well worth the time to learn classes first at one of the online sites like this one <a href="http://www.greenteapress.com/thinkpython/html/thinkpython016.html" rel="nofollow">http://www.greenteapress.com/thinkpython/html/thinkpython016.html</a> More here <a href="https://wiki.python.org/moin/BeginnersGuide/NonProgrammers" rel="nofollow">https://wiki.python.org/moin/BeginnersGuide/NonProgrammers</a><br /> You aren't going to get many answers with the way the program is structured because most programmers use the class structure AFAIK, so do not know how to pound the code into a non-class environment, so will not have any answers. If the first program below used classes then the second program's class could be inherited, and the functions would become part of the first program's class and could be accessed in the same way as the existing classes, so no passing of pointers, or any other hack, would be necessary.

## I deleted some code for simplicity def myfunction(event): canvas.configure(scrollregion=canvas.bbox("all"),width=300,height=200) def test(): TG.secondWindow() root = tk.Tk() root.geometry("600x350+30+50") myframe = tk.Frame(root,relief="groove",bd=1) myframe.place(x=20, y=30, width=560, height=200 ) canvas = tk.Canvas(myframe) frame = tk.Frame(canvas) myscrollbar=tk.Scrollbar(myframe, orient="vertical", command=canvas.yview) canvas.configure(yscrollcommand=myscrollbar.set) myscrollbar.pack(side="right", fill="y") canvas.pack(side="left") canvas.create_window((0,0), window=frame, anchor='nw') # what's bind really doing? frame.bind("<Configure>", myfunction) test = tk.Button(root, command=test, text="TEST", bg="lightblue") test.place(x = 20, y = 250, width=580, height=40) tk.Button(root, text="Quit All", command=root.quit, bg="orange").place(x=20, y=300) """ instance of the class in the imported program a pointer to the root window and the Tk instance are passed """ TG=target.Target(tk, root) tk.mainloop()

And target.py. Notice there are no imports.

class Target(): def __init__(self, tk, root): self.tk=tk self.root=root def changeMainWindow(self): # here's where I'm stuck self.tk.Label(self.amWin, bg="yellow", text =""""What do I have to do to add a new label in the main window from here? Or to delete it?""").place(x=50,y=20) def secondWindow(self): self.amWin = self.tk.Toplevel(self.root) self.amWin.geometry("300x200+720+50") button = self.tk.Button(self.amWin, text="Add Label", command=self.changeMainWindow) button.place(x = 20, y = 90, width=260, height=30).

Recommend

  • My table contains duplicate rows, how to show one?
  • How to speed up tkinter embedded matplot lib and python
  • How to detect WHICH folders OneDrive for Business are syncing
  • Python Tk windows hangs up
  • Java method that runs when window is opened
  • Plot 4 points based on the distance between them?
  • Bootstrap 4 carousel responsive issue in chrome
  • Python Tkinter: addressing Label widget created by for loop
  • Javascript and PHP (window.open)
  • Why is the output of print in python2 and python3 different with the same string?
  • PHP - Mysqli | i'm trying to output data but i keep getting empty array
  • Python Tkinter: addressing Label widget created by for loop
  • how get no border effect in tkinter ttk?
  • I want to handle a clickbutton event from another page
  • Java 8: Collector groupby with list nested class
  • How to draw graph inside swing with GraphStream actually?
  • Button commands in Tkinter
  • Expression simplification in SymPy
  • Encoded unicode characters lost
  • Python Programming 3.4.2, Naughts and Crosses. Best way to check how to see if game is won?
  • How to layout nodes once in GraphStream?
  • Deserializing JSON to a .net base class with JSON.net
  • Dynamically create button using Tkinter
  • Python : How to center Label in tkinter window
  • What does this mean? (Google Maps API)
  • Simple Distributed Erlang
  • Removing Duplicate Geometries
  • Retrieving specified columns from a list of csv files to create a data data frame in R
  • For loop with if condition on multiple R functions
  • as3-flash: any way to access all the instances placed in different frames from document class?
  • wxPython: displaying multiple widgets in same frame
  • Chart.js Multiple dataset
  • How to use carriage return with multiple line?
  • R - Combining Columns to String Based on Logical Match
  • Why HTML5 Canvas with a larger size stretch a drawn line?
  • Weird JavaScript statement, what does it mean?
  • embed rChart in Markdown
  • need help with bizarre java.net.HttpURLConnection behavior
  • Unable to use reactive element in my shiny app
  • Android Heatmap on canvas or ImageView