Tkinter reuse the same thread for another command? - python

The problem:
I would like to use this with an ESP32, to automate cli insructions. I have two buttons, the "Lets Go!!" button and the "Connect" button. "Connect" triggers def run which triggers def test and the command "rfq tty -P /dev/ttyUSB0", which will have some output displayed in the text box. I would like to use "Lets Go!!" to issue commands to that same thread/instance since it will be connected to the ESP32 with the "Connect" button.
Other:
I was able to adapt the terminal output found here (Redirect terminal output to tkinter). This is a work in progress, so the combo boxes don't trigger anything at this point. In the future I would like to .get() their values, and pass them as strings via the "Connect" button above.
Thank you for any help. Here is my code:
import tkinter as tk
from tkinter import messagebox, ttk
import sys
import subprocess
import threading
# --- classes ---
class Redirect():
def __init__(self, widget, autoscroll=True):
self.widget = widget
self.autoscroll = autoscroll
def write(self, text):
self.widget.insert('end', text)
if self.autoscroll:
self.widget.see("end") # autoscroll
# --- functions ---
def run():
threading.Thread(target=test).start()
def test():
p = subprocess.Popen("rfq tty -P /dev/ttyUSB0".split(), stdout=subprocess.PIPE, bufsize=1, text=True)
while p.poll() is None:
msg = p.stdout.readline().strip() # read a line from the process output
if msg:
print(msg)
# --- main ---
root = tk.Tk()
# - Frame with Text
width= root.winfo_screenwidth()
height= root.winfo_screenheight()
root.geometry("%dx%d" % (width, height))
frame = tk.Frame(root)
frame.pack(expand=True, fill='both')
serial = tk.Text(frame, width=50, height=1)
serial.place(x=48, y=7)
txrx = ttk.Combobox(
frame,
state="readonly",
values=["Tx", "Rx"]
)
txrx.place(x=50, y=50)
rxtxlabel= tk.Label(frame, text="Tx/Rx")
rxtxlabel.place(in_=txrx, relx=0, x=0, rely=1.5)
freq = ttk.Combobox(
frame,
state="readonly",
values=["315","433","868"]
)
freq.place(in_=txrx, relx=1.0, x=20, rely=0)
freqlabel= tk.Label(frame, text="Freq")
freqlabel.place(in_=freq, relx=0, x=0, rely=1)
mod = ttk.Combobox(
frame,
state="readonly",
values=["OOK","2-FSK","4-FSK", "MSK"]
)
mod.place(in_=freq, relx=1.0, x=20, rely=0)
modlabel= tk.Label(frame, text="Modulation")
modlabel.place(in_=mod, relx=0, x=0, rely=1)
text = tk.Text(frame, width=width, height=20)
text.place(x=0, y=300)
old_stdout = sys.stdout
sys.stdout = Redirect(text)
# - rest -
button = tk.Button(root, text='Lets Go!!', command=run)
button.place(in_=mod, relx=1, x=0, rely=0, y=210)
button = tk.Button(root, text='connect', command=run)
button.place(in_=serial, relx=1, x=10, rely=0, y= -4)
root.mainloop()
# - after close window -
sys.stdout = old_stdout

This works as tested with ping on both buttons. I am unsure if they are in the same instance though. I need to put together my esp32 setup to really test.
import tkinter as tk
from tkinter import messagebox, ttk
import sys
import subprocess
import threading
# --- classes ---
class Redirect():
def __init__(self, widget, autoscroll=True):
self.widget = widget
self.autoscroll = autoscroll
def write(self, text):
self.widget.insert('end', text)
if self.autoscroll:
self.widget.see("end") # autoscroll
# --- functions ---
def run():
text = serial.get(1.0, "end-1c")
threading.Thread(target=test("%s" % text)).start()
def test(variable):
p = subprocess.Popen(("%s" % variable).split(), stdout=subprocess.PIPE, bufsize=1, text=True)
while p.poll() is None:
msg = p.stdout.readline().strip() # read a line from the process output
if msg:
print(msg)
# --- main ---
root = tk.Tk()
# - Frame with Text
width= root.winfo_screenwidth()
height= root.winfo_screenheight()
root.geometry("%dx%d" % (width, height))
frame = tk.Frame(root)
frame.pack(expand=True, fill='both')
serial = tk.Text(frame, width=50, height=1)
serial.place(x=48, y=7)
txrx = ttk.Combobox(
frame,
state="readonly",
values=["Tx", "Rx"]
)
txrx.place(x=50, y=50)
rxtxlabel= tk.Label(frame, text="Tx/Rx")
rxtxlabel.place(in_=txrx, relx=0, x=0, rely=1.5)
freq = ttk.Combobox(
frame,
state="readonly",
values=["315","433","868"]
)
freq.place(in_=txrx, relx=1.0, x=20, rely=0)
freqlabel= tk.Label(frame, text="Freq")
freqlabel.place(in_=freq, relx=0, x=0, rely=1)
mod = ttk.Combobox(
frame,
state="readonly",
values=["OOK","2-FSK","4-FSK", "MSK"]
)
mod.place(in_=freq, relx=1.0, x=20, rely=0)
modlabel= tk.Label(frame, text="Modulation")
modlabel.place(in_=mod, relx=0, x=0, rely=1)
text = tk.Text(frame, width=width, height=20)
text.place(x=0, y=300)
old_stdout = sys.stdout
sys.stdout = Redirect(text)
# - rest -
button = tk.Button(root, text='Lets Go!!', command=lambda: test('ping -c 4 google.com'))
button.place(in_=mod, relx=1, x=0, rely=0, y=210)
button = tk.Button(root, text='connect', command=run)
button.place(in_=serial, relx=1, x=10, rely=0, y= -4)
root.mainloop()
# - after close window -
sys.stdout = old_stdout

Related

How change tkinter Notebook tab and keep configuration?

I have a gui with two tabs and would like to switch back and forth between the tabs while keeping the content of the tabs. If I do this all in one function, then it works fine, but since I have more in the individual functions. I have outsourced them. Now I have bound the individual functions to the tabs. But here I have the problem that I overwrite the tabs with every change. But I would like to switch between the tabs without overwriting the entries. I understand why I overwrite the input. After all, I call the individual functions with rountine and overwrite them that way. Unfortunately I do not know how to do it better.
import tkinter as tk
from tkinter import ttk
class display():
def __init__(self):
self.root = tk.Tk()
self.root.geometry('400x300')
self.root.title('Notebook Demo')
def gui(self):
# create a notebook
self.notebook = ttk.Notebook(self.root)
self.notebook.place(rely=0.0, relheight=1, relwidth=1)
# create frames
self.frame1 = ttk.Frame(self.notebook, width=400, height=280)
self.frame2 = ttk.Frame(self.notebook, width=400, height=280)
self.frame1.place(rely=0.0, relheight=1, relwidth=1)
self.frame2.place(rely=0.0, relheight=1, relwidth=1)
# add frames to notebook
self.notebook.add(self.frame1, text='General Information')
self.notebook.add(self.frame2, text='Profile')
self.notebook.bind("<<NotebookTabChanged>>", self.routine)
self.gu1()
self.root.update_idletasks()
self.root.mainloop()
def routine(self,event):
if self.notebook.index("current") == 1:
self.gu1()
else:
self.gu2()
def gu1(self):
button1 = tk.Button(self.frame1, text="test1", command=self.changeText)
button1.grid(column=0, row=0)
self.label1 = tk.Label(self.frame1, text="test1")
self.label1.grid(column=1, row=0)
self.root.mainloop()
def gu2(self):
button2 = tk.Button(self.frame2, text="test2", command=self.changeText2)
button2.grid(column=0, row=0)
self.label2 = tk.Label(self.frame2, text="test2")
self.label2.grid(column=1, row=0)
self.root.mainloop()
def changeText(self):
self.label1["text"] = "change1"
def changeText2(self):
self.label2["text"] = "change2"
if __name__ == "__main__":
display().gui()
All problem is that you use .gu1() and .gu2() in routine().
You should run .gu1() and .gu2() only once - at start in gui().
def gui(self):
# ... code ...
self.notebook.bind("<<NotebookTabChanged>>", self.routine)
self.gu1() # create at start
self.gu2() # create at start
def routine(self,event):
if self.notebook.index("current") == 1:
#self.gu1() # DON'T DO THIS
print('selected tab 1')
else:
#self.gu2() # DON'T DO THIS
print('selected tab 2')
Working code:
tkinter should use only one mainloop()
import tkinter as tk
from tkinter import ttk
class display():
def __init__(self):
self.root = tk.Tk()
self.root.geometry('400x300')
self.root.title('Notebook Demo')
def gui(self):
# create a notebook
self.notebook = ttk.Notebook(self.root)
self.notebook.place(rely=0.0, relheight=1, relwidth=1)
# create frames
self.frame1 = ttk.Frame(self.notebook, width=400, height=280)
self.frame2 = ttk.Frame(self.notebook, width=400, height=280)
self.frame1.place(rely=0.0, relheight=1, relwidth=1)
self.frame2.place(rely=0.0, relheight=1, relwidth=1)
# add frames to notebook
self.notebook.add(self.frame1, text='General Information')
self.notebook.add(self.frame2, text='Profile')
self.notebook.bind("<<NotebookTabChanged>>", self.routine)
self.gu1()
self.gu2()
self.root.update_idletasks()
self.root.mainloop()
def routine(self,event):
if self.notebook.index("current") == 1:
#self.gu1() # DON'T DO THIS
print('selected tab 1')
else:
#self.gu2() # DON'T DO THIS
print('selected tab 2')
def gu1(self):
button1 = tk.Button(self.frame1, text="test1", command=self.changeText)
button1.grid(column=0, row=0)
self.label1 = tk.Label(self.frame1, text="test1")
self.label1.grid(column=1, row=0)
def gu2(self):
button2 = tk.Button(self.frame2, text="test2", command=self.changeText2)
button2.grid(column=0, row=0)
self.label2 = tk.Label(self.frame2, text="test2")
self.label2.grid(column=1, row=0)
def changeText(self):
self.label1["text"] = "change1"
def changeText2(self):
self.label2["text"] = "change2"
if __name__ == "__main__":
display().gui()
EDIT:
If you have to create some widgets in tabs with delays (ie. to wait for user's values in other widgets) then you should use boolean variables (True/False) to run it only once in routine()
def gui(self):
# ... code ...
self.gu1_created = False
self.gu2_created = False
self.notebook.bind("<<NotebookTabChanged>>", self.routine)
def routine(self,event):
if self.notebook.index("current") == 1:
if not self.gu1_created:
self.gu1()
self.gu1_created = True
print('selected tab 1')
else:
if not self.gu2_created:
self.gu2()
self.gu2_created = True
print('selected tab 2')

Modules and classes in Python for a desktop application

This is to be a desktop application for opening multiple small databases and running queries on them. So far I've written some code for opening forms as necessary. Is this a good way to do it? Also - the code shown opens two copies of each form - what am I doing wrong? It's my first attempt at Python and I'm a rudimentary programmer so simple answers would be of most help please. TIA (Python 3.9.6)
link_1.py
from tkinter import Tk
import link_2
root = Tk()
class ClassLink_1:
#if another function in the class is called, the __init__ function is run at start up
def __init__(self):
print("in link_1 __init__ instruction")
#the call_function function can be called at start up, or not, and will act accordingly
def call_function(self):
print("in call_function")
#the line below is run at start up whether or not another function in the class is called
print("in link_1")
root.withdraw() #hides the blank form at start up
#if __name__ == "__main__":
#the line below shows the link_2 form, whether or not the if __name__==__main__ condition is used as its condition
link_2.ClassLink_2(root).__init__(root)
#link_3.ClassLink_3(root).__init__(root)
#the line below runs call_function on start up to print text
ClassLink_1().call_function()
root.mainloop()
link_2.py
from tkinter import Tk, Button
from tkinter import * #for Toplevel
import link_3
root = Tk()
class ClassLink_2:
def __init__(self, master):
self.openNewWindow()
def openNewWindow(self):
newWindow = Toplevel(root) #creates a top level widget with the parent root (first parameter)
newWindow.title("Title opened from link_1")
newWindow.geometry("500x500")
label = Label(newWindow, text ="Opened from link_1").grid(row=1, column=1)
self.add_button = Button(newWindow, text="in ClassLink_2", command= self.do_add)
self.add_button.grid(row=3, column=1)
def do_add(self):
print("button pressed")
link_3.ClassLink_3(root).__init__(root)
root.withdraw() #hides the blank form at start up
link_3.py
from tkinter import Tk, Button
from tkinter import * #for Toplevel
root = Tk()
class ClassLink_3:
def __init__(self, master):
self.openNewWindow()
def openNewWindow(self):
newWindow = Toplevel(root) #creates a top level widget with the parent root (first parameter)
newWindow.title("Title opened from link_2")
newWindow.geometry("500x500")
label = Label(newWindow, text ="Opened from link_2").grid(row=1, column=1)
self.add_button = Button(newWindow, text="in ClassLink_3", command= self.do_add)
self.add_button.grid(row=3, column=1)
def do_add(self):
print("button pressed")
# link_4.ClassLink_4(root).__init__(root) this file has not yet been made
root.withdraw() #hides the blank form at start up
This is a proposed solution, can be expanded as needed. Constructive suggestions for improvement of the structure or code would be appreciated. TIA. I've left in the details in case they are of use to anyone.
link_1
from tkinter import Tk
import link_2
root = Tk()
class ClassLink_1:
def __init__(self):
print("in link_1 __init__ instruction")
root.withdraw() #hides the blank form at start up
link_2.ClassLink_2(root).openNewWindow(0)
root.mainloop()
link_2
from tkinter import Tk, Button
from tkinter import *
import link_3
root = Tk()
class ClassLink_2:
root.withdraw() #hides the blank form at start up
class_var_1 = 0
inst_var_1 = 0
def __init__(self, incoming_inst_var_1):
pass
def openNewWindow(self, inst_var_1_to_open):
newWindow = Toplevel(root)
newWindow.title("Title opened from link_1")
newWindow.geometry("500x500")
label = Label(newWindow, text ="Opened from link_1").grid(row=1, column=1)
self.add_button = Button(newWindow, text="in ClassLink_2", command= self.do_add)
self.add_button.grid(row=3, column=1)
self.add_button = Button(newWindow, text="increment class_var_1", command= self.inc_class_var_1)
self.add_button.grid(row=5, column=1)
self.inst_var_1 = inst_var_1_to_open
def do_add(self):
print("button pressed")
link_3.ClassLink_3(root).openNewWindow(0)
def inc_class_var_1(self):
ClassLink_2.class_var_1 += 2
self.inst_var_1 += 1
print("self.class_var_1 = " + (str)(self.class_var_1))
print("self.inst_var_1 = " + (str)(self.inst_var_1))
link_3
from tkinter import Tk, Button
from tkinter import *
from tkinter.ttk import Combobox
import tkinter.scrolledtext as tkscrolled
# import link_4 <filename of next form>
root = Tk()
class ClassLink_3:
class_var_1 = 0
inst_var_1 = 0
# ------------------------------- START CLASS CONTROLS -----------------------------
root.withdraw()
def __init__(self, incoming_inst_var_1):
pass
def openNewWindow(self, inst_var_1_to_open):
new_window = Toplevel(root)
self.widget_factory(new_window)
self.inst_var_1 = inst_var_1_to_open
def do_add(self):
print("button pressed")
# link_4.ClassLink_4(root).openNewWindow(0) # <filename of next form>
# ---------------------------------- END CLASS CONTROLS -----------------------------
# -------------------------------------- START CALCS --------------------------------------
def inc_class_var_1(self):
ClassLink_3.class_var_1 += 2
self.inst_var_1 += 1
print("self.class_var_1 = " + (str)(self.class_var_1))
print("self.inst_var_1 = " + (str)(self.inst_var_1))
# ---------------------------------------- END CALCS --------------------------------------
# ---------------------------------------- START FACTORY SHOPS-----------------------------------------
def widget_factory(self, new_window):
self.shop_window(new_window)
self.shop_labels(new_window)
self.shop_buttons(new_window)
self.shop_menu(new_window)
self.shop_listbox(new_window)
self.shop_combobox(new_window)
self.shop_radiobuttons(new_window)
self.shop_checkbuttons(new_window)
self.shop_entries(new_window)
self.shop_canvas(new_window)
self.shop_scale(new_window)
self.shop_scrollbars(new_window)
self.shop_textbox(new_window)
self.shop_menu(new_window)
pass
# ------------------------
def shop_window(self, new_window):
new_window.title("Title opened from link_2")
new_window.geometry("800x900")
def shop_labels(self, new_window):
self.label_1 = Label(new_window, text ="Opened from link_2").grid(row=1, column=1)
def shop_buttons(self, new_window):
self.button_1 = Button(new_window, text="in ClassLink_3", command= self.do_add)
self.button_1.grid(row=3, column=1)
self.button_2 = Button(new_window, text="increment class_var_1", command= self.inc_class_var_1)
self.button_2.grid(row=5, column=1)
def shop_listbox(self, new_window):
data=("one", "two", "three", "four")
self.listbox_1 = Listbox(new_window, height=5, selectmode='multiple')
for num in data:
self.listbox_1.insert(END,num)
self.listbox_1.grid(row=7, column=1)
def shop_combobox(self, new_window):
data=("one", "two", "three", "four")
self.combobox_1 = Combobox(new_window, values=data)
self.combobox_1.grid(row=8, column=3)
def shop_radiobuttons(self, new_window):
var_1 = IntVar()
var_1.set(1)
self.rad_btn_1 = Radiobutton(new_window, text="male", variable=var_1, value=1)
self.rad_btn_2 = Radiobutton(new_window, text="female", variable=var_1, value=2)
self.rad_btn_1.grid(row=9, column=1)
self.rad_btn_2.grid(row=9, column=2)
def shop_checkbuttons(self, new_window):
var_1 = IntVar()
var_2 = IntVar()
self.checkbtn_1 = Checkbutton(new_window, text = "Cricket", variable = var_1)
self.checkbtn_2 = Checkbutton(new_window, text = "Tennis", variable = var_2)
self.checkbtn_1.grid(row=10, column=1)
self.checkbtn_2.grid(row=10, column=2)
def shop_entries(self, new_window):
self.entry_1 = Entry(new_window, width = 20)
self.entry_1.insert(0,'Username')
self.entry_1.grid(row= 11, column=2)
self.entry_2 = Entry(new_window, width = 15)
self.entry_2.insert(0,'password')
self.entry_2.grid(row= 12, column=2)
#might want to place on a frame, see example https://coderslegacy.com/python/list-of-tkinter-widgets/
def shop_canvas(self, new_window):
canvas = Canvas(new_window, bg= 'white', width = 260,height = 260) #this is the background for the figure
# left and top of figure is from [x from left, y from top] of canvas right and bottom of figure from [x from left, y from top] of canvas
coordinates = 20, 50, 210, 230
arc = canvas.create_arc(coordinates, start=0, extent=250, fill="blue") #start is from E, extent is in degrees CCW
arc = canvas.create_arc(coordinates, start=250, extent=50, fill="red")
arc = canvas.create_arc(coordinates, start=300, extent=60, fill="yellow")
canvas.grid(row=2, column=1)
def shop_scale(self, new_window):
self.scale_1 = Scale(new_window, from_=0, to=10, orient=VERTICAL)
self.scale_1.grid(row=15, column=2)
self.scale_2 = Scale(new_window, from_=0, to=10, orient = HORIZONTAL)
self.scale_2.grid(row=15, column=3)
def shop_scrollbars(self, new_window):
self.scroll_vert = Scrollbar(new_window)
self.scroll_vert.grid(row=19, column=3)
self.listbox_3 = Listbox(new_window, yscrollcommand = self.scroll_vert.set )
for line in range(1, 100):
self.listbox_3.insert(END, "Number " + str(line))
self.listbox_3.grid(row=19 , column=2)
self.scroll_vert.config(command = self.listbox_3.yview)
def shop_textbox(self, new_window):
#make a frame with parent new_window
self.frame_textbox_1 = Frame(new_window)
self.frame_textbox_1.grid(row=1, column=5)
#make the textbox with parent frame
self.textbox_1 = Text(self.frame_textbox_1)
self.textbox_1.config(wrap=NONE, width=15, height=8) #width, height are characters x rows permitted wrap values should be WORD CHAR, or NONE
#make the X scrollbar with parent frame
self.scroll_text_horiz = Scrollbar(self.frame_textbox_1, orient="horizontal")
self.scroll_text_horiz.config(command = self.textbox_1.xview)
#make the Y scrollbar with parent frame
self.scroll_text_vert = Scrollbar(self.frame_textbox_1, orient="vertical")
self.scroll_text_vert.config(command = self.textbox_1.yview)
#pack the scrollbars before the texbox to allow them to fill the frame width and height
self.scroll_text_horiz.pack(side=BOTTOM, fill=X)
self.scroll_text_vert.pack(side=RIGHT, fill=Y)
self.textbox_1.pack(fill="y")
#connect the scrollbars to the textbox
self.textbox_1["xscrollcommand"] = self.scroll_text_horiz.set
self.textbox_1["yscrollcommand"] = self.scroll_text_vert.set
message = "the quick brown fox"
self.textbox_1.insert(1.1, message)
# ----------------------------------------------
def shop_menu(self, new_window):
print("in shop menu1")
menubar = Menu(new_window)
print("in shop_menu2")
file = Menu(menubar, tearoff=0)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save as...")
file.add_command(label="Close")
file.add_separator()
file.add_command(label="Exit", command=new_window.quit)
menubar.add_cascade(label="File", menu=file)
edit = Menu(menubar, tearoff=0)
edit.add_command(label="Undo")
edit.add_separator()
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Delete")
edit.add_command(label="Select All")
menubar.add_cascade(label="Edit", menu=edit)
help = Menu(menubar, tearoff=0)
help.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)
new_window.config(menu=menubar)
print("in shop menu3")
# --------------------------------------- END FACTORY SHOPS---------------------------------------

Python - Tkinter - invisible text in ttk.Entry in sub window

I'm trying to make a sub window for configuration settings. But the text in the sub window is invisible. I am reading correctly but I cannot see the text. Below is my sample code with the problem:
import tkinter as tk
from tkinter import ttk
from tkinter import Menu
class Frames:
def __init__(self):
self.port_com = None
def main_frame(self, win):
# Main Frame
main = ttk.LabelFrame(win, text="")
main.grid(column=0, row=0, sticky="WENS", padx=10, pady=10)
return main
def dut_configuration_frame(self, win):
# Configuration Frame
dut_config_frame = ttk.LabelFrame(win, text="Config")
dut_config_frame.grid(column=0, row=0, sticky='NWS')
# Port COM
ttk.Label(dut_config_frame, text="Port COM").grid(column=0, row=0)
self.port_com = tk.StringVar()
ttk.Entry(dut_config_frame, width=12, textvariable=self.port_com).grid(column=0, row=1, sticky=tk.EW)
self.port_com.set(value="COM7")
print(self.port_com.get())
class ConfigFrames:
def __init__(self):
self.port_com = None
def main_frame(self, win):
# Main Frame
main = ttk.LabelFrame(win, text="")
main.grid(column=0, row=0, sticky="WENS", padx=10, pady=10)
return main
def configuration_frame(self, win):
# Configuration Frame
dut_config_frame = ttk.LabelFrame(win, text="Config")
dut_config_frame.grid(column=0, row=0, sticky='NWS')
# Port COM
ttk.Label(dut_config_frame, text="Port COM").grid(column=0, row=0)
self.port_com = tk.StringVar()
ttk.Entry(dut_config_frame, width=12, textvariable=self.port_com).grid(column=0, row=1, sticky=tk.EW)
self.port_com.set(value="COM5")
print(self.port_com.get())
def menu_bar(win):
def _config():
config_frame = ConfigFrames()
config_window = tk.Tk()
config_window.title("Sub window")
config_window.geometry("200x200")
config_window.resizable(0, 0)
main = config_frame.main_frame(config_window)
config_frame.configuration_frame(main)
config_window.mainloop()
# Menu
menuBar = Menu(win)
win.config(menu=menuBar)
settingsMenu = Menu(menuBar, tearoff=0)
settingsMenu.add_command(label="Config", command=_config)
menuBar.add_cascade(label="Settings", menu=settingsMenu)
frames = Frames()
win = tk.Tk()
win.title("Main window")
win.geometry("200x200")
win.resizable(0, 0)
menu_bar(win)
main = frames.main_frame(win)
frames.dut_configuration_frame(win)
win.mainloop()
As you can see in main window it is visible, but in sub window it is invisible.
And printing in console is correct:

Using .get() within tkinter ScrolledFrame

I am trying to achieve grabbing par02_1 using .get(). I have success writing the rest of the .txt file but my program is not grabbing my gui entry lines. I'm guessing this has something to do with the association self, and the scrollable section, etc. but I can't track this one down. Any help is appreciated.
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import time
root = Tk()
# GUI Window
root.title("Outfile Automation")
# Gui Future Menu Logic
def future01():
print("Future Command 01")
# GUI Main Menu
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New Script...", command=future01)
subMenu.add_separator()
subMenu.add_command(label="Exit Program", command=future01)
helpMenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpMenu, command=future01)
helpMenu.add_command(label="Instruction Manual", command=future01)
helpMenu.add_command(label="Software Version: A0.003")
##Scrollbar
class VerticalScrolledFrame(Frame):
def __init__(self, parent, *args, **kw):
Frame.__init__(self, parent, *args, **kw)
# create a canvas object and a vertical scrollbar for scrolling it
vscrollbar = Scrollbar(self, orient=VERTICAL)
vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
canvas = Canvas(self, bd=0, highlightthickness=0,
yscrollcommand=vscrollbar.set)
canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
vscrollbar.config(command=canvas.yview)
# reset the view
canvas.xview_moveto(0)
canvas.yview_moveto(0)
# create a frame inside the canvas which will be scrolled with it
self.interior = interior = Frame(canvas)
interior_id = canvas.create_window(0, 0, window=interior,
anchor=NW)
# track changes to the canvas and frame width and sync them,
# also updating the scrollbar
def _configure_interior(event):
# update the scrollbars to match the size of the inner frame
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the canvas's width to fit the inner frame
canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the inner frame's width to fill the canvas
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
canvas.bind('<Configure>', _configure_canvas)
if __name__ == "__main__":
class AutoApp(Tk):
def __init__(self, *args, **kwargs):
root = Tk.__init__(self, *args, **kwargs)
self.frame = VerticalScrolledFrame(root)
self.frame.pack()
self.label = Label(text="")
self.label.pack()
self.par02_1 = StringVar()
title_1 = Label(self.frame.interior, text="Device IP (DHCP)", fg="blue", font="Verdana 10 underline")
title_1.pack()
label_1 = Label(self.frame.interior, text="Device 01")
label_1.pack()
entry_1 = Entry(self.frame.interior, textvariable=self.par02_1)
entry_1.pack()
outFile = open('CSC.txt', 'wt')
outFile.write("[Script Header]\nDebugStrings=on\nAbortOnError=on\nConcurrentSectionLimit=230\n"
"//23 Devices if necessary""\n\n[Variables]""\n"
+ (self.par02_1.get()) + "\n\n"
"[Device01]\nConnect=tcp |proc01|\nRunAsSingleTransaction=on\nEthernetDHCPHost "
+ (self.par02_1.get()) + "EthernetCurrentConnectionInfo\n")
outFile.close()
def muser():
feedback_1 = Label(root, text="Creating Script...").pack()
feedback_2 = Label(root, text="Script Complete!").pack()
time.sleep(2)
return
# GUI Buttons
mbutton = Button(root, text="Create Script", command=muser, fg="black", bg='green')
mbutton.pack()
app = AutoApp()
app.mainloop()
Hello thank you both for your guidance as I learn proper syntax. I have a long way to go but you both helped point me in the right direction so I can get my program online. I stripped this down to the basics and will implement a variation of the following architecture in my actual code.
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import time
root = Tk()
# GUI Window
root.title("Outfile Automation")
# Gui Future Menu Logic
def future01():
print("Future Command 01")
# GUI Main Menu
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New Script...", command=future01)
subMenu.add_separator()
subMenu.add_command(label="Exit Program", command=future01)
helpMenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpMenu, command=future01)
helpMenu.add_command(label="Instruction Manual", command=future01)
helpMenu.add_command(label="Software Version: A0.003")
par02_1 = StringVar()
title_1 = Label(root, text="Device IP (DHCP)", fg="blue", font="Verdana 10 underline")
title_1.pack()
label_1 = Label(root, text="Device 01")
label_1.pack()
entry_1 = Entry(root, textvariable=par02_1)
entry_1.pack()
root.mainloop()
template = """[Script Header]\nDebugStrings=on\nAbortOnError=on\nConcurrentSectionLimit=230\n//23 Devices if necessary
\n\n[Variables]\n{}\n\n[Device01]\nConnect=tcp |proc01|\nRunAsSingleTransaction=on\nEthernetDHCPHost\nEthernetCurrentConnectionInfo\n"""
outFile = open('CSC.txt', 'wt')
outFile.write(template.format(par02_1.get()).rstrip())
outFile.close()
root.mainloop()

The horizontal scrollbar didn't work in Tkinter

I want to create a GUI program base on tkinter. One of the widgets is Text. I want to add a horizontal scrollbar in it, but it didn't work.
Where did I make a mistake?
from Tkinter import *
import tkFont
class DpWin(object):
def run(self):
root=Tk()
root.geometry('768x612')
title='dp'
root.title(title)
xscrollbar = Scrollbar(root, orient=HORIZONTAL)
xscrollbar.pack(side=BOTTOM, fill=X)
yscrollbar = Scrollbar(root)
yscrollbar.pack(side=RIGHT, fill=Y)
text = Text(root,xscrollcommand=xscrollbar.set,yscrollcommand=yscrollbar.set)
text.pack()
xscrollbar.config(command=text.xview)
yscrollbar.config(command=text.yview)
text.insert(END,'a'*999)
mainloop()
def start(self):
self.b_start.config(state=DISABLED)
self.b_stop.config(state=ACTIVE)
def stop(self):
self.b_stop.config(state=DISABLED)
self.b_start.config(state=ACTIVE)
if __name__=='__main__':
win=DpWin()
win.run()
I've modified your code according to here. There are 2 main differences.
I made it so the textbox doesn't wrap. If you wrap text, there is nothing for the horizontal scrollbar to scroll to.
I used the grid geometry manager on a frame to keep the scrollbars and text widgets together. The advantage to using .grid is that you actually get scrollbars which are the correct width/height (something you can't achieve with pack).
...
from Tkinter import *
import tkFont
class DpWin(object):
def run(self):
root=Tk()
root.geometry('768x612')
title='dp'
root.title(title)
f = Frame(root)
f.pack()
xscrollbar = Scrollbar(f, orient=HORIZONTAL)
xscrollbar.grid(row=1, column=0, sticky=N+S+E+W)
yscrollbar = Scrollbar(f)
yscrollbar.grid(row=0, column=1, sticky=N+S+E+W)
text = Text(f, wrap=NONE,
xscrollcommand=xscrollbar.set,
yscrollcommand=yscrollbar.set)
text.grid(row=0, column=0)
xscrollbar.config(command=text.xview)
yscrollbar.config(command=text.yview)
text.insert(END, 'a'*999)
mainloop()
def start(self):
self.b_start.config(state=DISABLED)
self.b_stop.config(state=ACTIVE)
def stop(self):
self.b_stop.config(state=DISABLED)
self.b_start.config(state=ACTIVE)
if __name__=='__main__':
win=DpWin()
win.run()
There is one comment regarding making both x and y scrollbars work within the pack framework. Here is a minimal example:
import tkinter as tk
from tkinter import X, Y, BOTTOM, RIGHT, LEFT, Y, HORIZONTAL
class TextExample(tk.Frame):
def __init__(self, master=None):
super().__init__()
sy = tk.Scrollbar(self)
sx = tk.Scrollbar(self, orient=HORIZONTAL)
editor = tk.Text(self, height=500, width=300, wrap='none')
sx.pack(side=BOTTOM, fill=X)
sy.pack(side=RIGHT, fill=Y)
editor.pack(side=LEFT, fill=Y)
sy.config(command=editor.yview)
sx.config(command=editor.xview)
self.pack()
def main():
root = tk.Tk()
root.geometry("800x500+0+0")
app = TextExample(master=root)
root.mainloop()
if __name__ == '__main__':
main()

Categories

Resources