I have a program called main.py:
def prog2():
exec(open("prog2.py").read())
buttonHMI = tk.Button(text="Program HMI", width=15, font=("Arial", 14), command=prog2)
buttonHMI.grid(column=0, row=3, columnspan=1, padx=20, pady=10, sticky=W)
So there's 1 button and when pressed it executes a 2nd program called prog2:
from tkinter import *
from tkinter import ttk
window = tk.Tk()
def close():
window.destroy
CB1 = Checkbutton(window, text="Enable VNC", font=("Arial", 12), variable=action_VNC)
CB1.grid(row=0, sticky=W, padx=10)
CB1.configure(bg='#34aeeb')
ButtonClose= tk.Button(window, text="Close", width=20, font=("Arial", 14), command=window.destroy)
ButtonClose.grid(columnspan=2, column = 3, row=9, sticky=W, padx=10, pady=10)
class Timer:
def __init__(self, window=None):
self.sv = tk.StringVar()
ButtonShow = tk.Button(window, text="Program HMI", width=20, font=("Arial", 14), command=self.actions)
ButtonShow.grid(columnspan=2, row=9, column = 0, sticky=W, padx=10, pady=10)
progress = ttk.Progressbar(window, orient = HORIZONTAL, length = 500, mode = 'determinate')
progress.grid(row=10, columnspan = 4, sticky=W, padx=10, pady=10)
outText = Text(window, width=50, height=20, wrap=WORD)
outText.grid(row=11, columnspan=4, padx=10)
###########################################################
#start actions.
def actions(self):
print("action")
Timer()
window.mainloop()
The problem I'm having is from main.py, I open prog2, some of the objects (Buttonshow, progress, outText) will show up in the main.py window. But CB1 and Close objects will show in prog2. If I execute prog2.py by itself, then all the objects will show correctly in prog2 window. How do I get all of prog2 objects to show in prog2?
Related
There are four buttons that hide or show a canvas. When I clicked the first time it work but then I don't really know it doesn't work. I made the buttons global because I need to reposition them depending on the canvas. How can I fix this? The function show_shares and show_DividendGrowth are the single ones that are used and they are creating some table cells and charts.
from tkinter import ttk
import pygsheets
from tkinter import *
from Shares import show_shares
from DividendGrowth import show_DividendGrowth
from MonthlyDividend import show_MonthlyDividend
from Evolution import showEvolution
client = pygsheets.authorize(service_account_file="dividend-portfolio.json")
sh = client.open('Portfolio')
wk1 = sh.sheet1
window = Tk()
window.title('Dividend Portfolio')
window.attributes('-fullscreen', True)
container = ttk.Frame(window)
container.pack(fill="both", expand=1)
canvas = Canvas(container)
scrollable_frame = ttk.Frame(canvas)
scrollbar_vertical = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
scrollbar_vertical.pack(side="right", fill="y")
canvas.configure(yscrollcommand=scrollbar_vertical.set)
canvas.bind('<Configure>', lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.pack(fill=BOTH, expand=1)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
current_page = [0, 0, 0, 0]
shares_canvas = Canvas(scrollable_frame)
dividendGrowth_canvas = Canvas(scrollable_frame)
monthlyDividend_canvas = Canvas(scrollable_frame)
evolution_canvas = Canvas(scrollable_frame)
global shares_button, dividendGrowth_button, monthlyDividend_button, evolution_button
def placeButtons(master):
global shares_button, dividendGrowth_button, monthlyDividend_button, evolution_button
shares_button = Button(master, text="Actiuni", borderwidth=2,relief="solid", width=9, height=1, font=("Calibri", 13), bg="dodgerblue", fg="white")
dividendGrowth_button = Button(master, text="Dividende si cresteri", borderwidth=2, relief="solid", width=16, height=1, font=("Calibri", 13), bg="dodgerblue", fg="white")
monthlyDividend_button = Button(master, text="Dividende lunare", borderwidth=2, relief="solid", width=14, height=1, font=("Calibri", 13), bg="dodgerblue", fg="white")
evolution_button = Button(master, text="Evolutie", borderwidth=2,relief="solid", width=9, height=1, font=("Calibri", 13), bg="dodgerblue", fg="white")
def start(current_page):
if current_page[0] == 0:
current_page = [1, 0, 0, 0]
show_shares(shares_canvas)
shares_canvas.grid()
dividendGrowth_canvas.grid_forget()
monthlyDividend_canvas.grid_forget()
evolution_canvas.grid_forget()
placeButtons(shares_canvas)
shares_button.grid(row=102, column=0, columnspan=2, padx=6, pady=4, sticky=W)
dividendGrowth_button.grid(row=102, column=0, columnspan=3, padx=90, pady=4, sticky=E)
monthlyDividend_button.grid(row=102, column=1, columnspan=4, padx=47, sticky=W)
evolution_button.grid(row=102, column=3, columnspan=4, padx=56, sticky=W)
start(current_page)
def showShares(event, current_page):
start(current_page)
def showDividendGrowth(event, current_page):
if current_page[1] == 0:
current_page = [0, 1, 0, 0]
shares_canvas.grid_forget()
monthlyDividend_canvas.grid_forget()
evolution_canvas.grid_forget()
show_DividendGrowth(dividendGrowth_canvas)
dividendGrowth_canvas.grid()
placeButtons(dividendGrowth_canvas)
shares_button.grid(row=102, column=0, columnspan=2, padx=6, pady=4, sticky=W)
dividendGrowth_button.grid(row=102, column=0, columnspan=4, padx=101, pady=4, sticky=W)
monthlyDividend_button.grid(row=102, column=1, columnspan=5, padx=157, sticky=W)
evolution_button.grid(row=102, column=3, columnspan=4, padx=53, sticky=W)
scrollbar_orizontal = ttk.Scrollbar(container, orient="horizontal", command=canvas.xview)
scrollbar_orizontal.pack(side="bottom", fill="x")
canvas.configure(xscrollcommand=scrollbar_orizontal.set)
shares_button.bind('<Button-1>', lambda event: show_shares(event))
dividendGrowth_button.bind('<Button-1>', lambda event: showDividendGrowth(event, current_page))
window.mainloop()
Python TKinter Mac: Buttons layout strangely and when a button is clicked it looks the same (as if it hadn't been clicked) however I didn't check to see if the button worked.
and the space is a textbook
the Mac version is: a 2017 iMac running Monterey 12.4
import tkinter as tk
window = tk.Tk()
window.geometry("500x500")
window.title("Stock Watchlist & Logger")
label = tk.Label(window, text="Tester", font=('Ariel', 18))
label.pack(padx=20, pady=20)
textbox = tk.Text(window, height=3, font=('Ariel', 16))
textbox.pack(padx=10, pady=10)
numbuttframe = tk.Frame(window)
numbuttframe.columnconfigure(0, weight=1)
yesnobuttframe = tk.Frame(window)
yesnobuttframe.columnconfigure(1, weight=1)
button1 = tk.Button(numbuttframe, text="1", font=('Arial', 18))
button1.grid(row=0, column=0, sticky=tk.W+tk.E)
button2 = tk.Button(numbuttframe, text="2", font=('Arial', 18))
button2.grid(row=0, column=1, sticky=tk.W+tk.E)
button3 = tk.Button(numbuttframe, text="3", font=('Arial', 18))
button3.grid(row=0, column=2, sticky=tk.W+tk.E)
button4 = tk.Button(numbuttframe, text="4", font=('Arial', 18))
button4.grid(row=0, column=3, sticky=tk.W+tk.E)
button5 = tk.Button(numbuttframe, text="5", font=('Arial', 18))
button5.grid(row=0, column=4, sticky=tk.W+tk.E)
button6 = tk.Button(numbuttframe, text="6", font=('Arial', 18))
button6.grid(row=0, column=5, sticky=tk.W+tk.E)
yesbutton = tk.Button(yesnobuttframe, text="Yes", font=('Arial', 18))
yesbutton.grid(row=0, column=0, sticky=tk.W+tk.E)
nobutton = tk.Button(yesnobuttframe, text="No", font=('Arial', 18))
nobutton.grid(row=0, column=1, sticky=tk.W+tk.E)
numbuttframe.pack(fill='x')
yesnobuttframe.pack(fill='x')
if button1:
print("CELEBRATE!")
window.mainloop()
You set the weight to two cells weight=1 , so they expanded, since the rest have a default weight of 0. Since I don’t see your grid - the buttons are placed in frames one after the other, suggest using the pack method. And shortened your code a bit. The buttons won't work yet, because they don't have a command = call. Complex variable names in Python are usually written with an underscore.
import tkinter as tk
FONT = ('Ariel', 18)
window = tk.Tk()
window.geometry("500x500")
window.title("Stock Watchlist & Logger")
lbl = tk.Label(window, text="Tester", font=FONT)
lbl.pack(padx=20, pady=20)
text_box = tk.Text(window, height=3, font=('Ariel', 16))
text_box.pack(padx=10, pady=10)
num_btn = tk.Frame(window)
yes_no_btn = tk.Frame(window)
num_btn.pack(fill='x')
yes_no_btn.pack(fill='x')
buttons = []
for i in range(1, 7):
btn = tk.Button(num_btn, text=f"{i}", font=FONT)
btn.pack(side="left", fill='x', expand=True)
buttons.append(btn)
yes_btn = tk.Button(yes_no_btn, text="Yes", font=FONT)
yes_btn.pack(side="left", fill='x', expand=True)
no_btn = tk.Button(yes_no_btn, text="No", font=FONT)
no_btn.pack(side="left", fill='x', expand=True)
window.mainloop()
The purpose is to pull a word from the list randomly and display it on the screen in the GUI. The words are displayed in the terminal when I click the button "dammi" but I cannot get them to display in the GUI. I have tried both an Entry and Label with no success.
from tkinter import *
import random
# Window
root = Tk()
root.geometry("400x350")
root.title("Passato Remoto")
root.configure(bg="#000000")
root.resizable(False, False)
# Find Verb
verbi = ['Dare', 'Dire', 'Fare', 'Sapere', 'Prendere']
# Dammi Button
def give():
print(random.choice(verbi))
# Create Buttons
dammi = Button(root, text='Dammi un verbo',
bg='#ffffff',
fg='#000000',
borderwidth=0,
highlightthickness=0,
font=('Helvetica', 16),
height=2,
width=10,
command=give)
dammi.grid(column=0, row=2, pady=50, padx=25)
con = Button(root, text='Coniugazione',
bg='#ffffff',
fg='#000000',
borderwidth=0,
highlightthickness=0,
font=('Helvetica', 16),
height=2,
width=10)
con.grid(column=2, row=2, pady=50, padx=25)
# Put Verb On Screen
verb = Entry(root, text=give(), font=('Helvetica', 40), width=10, bg="#ffffff", fg="#000000")
verb.grid(column=0, columnspan=3, row=1, pady=50, padx=80)
root.mainloop()
The easiest way is probably to use a StringVar. I've added this into the question code.
from tkinter import *
import random
root = Tk()
root.geometry("400x350")
root.title("Passato Remoto")
root.configure(bg="#000000")
root.resizable(False, False)
# Find Verb
verbi = ['Dare', 'Dire', 'Fare', 'Sapere', 'Prendere']
# Dammi Button
sample = StringVar() # Added
def give(): # Changed
sample.set( random.choice(verbi) )
print( sample.get() )
# Create Buttons
dammi = Button(root, text='Dammi un verbo',
bg='#ffffff',
fg='#000000',
borderwidth=0,
highlightthickness=0,
font=('Helvetica', 16),
height=2,
width=10,
command=give)
dammi.grid(column=0, row=2, pady=50, padx=25)
con = Button(root, text='Coniugazione',
bg='#ffffff',
fg='#000000',
borderwidth=0,
highlightthickness=0,
font=('Helvetica', 16),
height=2,
width=10)
con.grid(column=2, row=2, pady=50, padx=25)
# Put Verb On Screen
# changed here
verb = Label(root, font=('Helvetica', 40), textvariable = sample, width=10, bg="#ffffff", fg="#000000")
verb.grid(column=0, columnspan=3, row=1, pady=50, padx=80)
give()
root.mainloop()
Can someone help, i need to generate 10 buttons and then when i click it must change the text on the unnamed button.
trying to get the event.widget but with no successes
from tkinter import ttk
root = ttk()
def gonow(e):
e.config(text="clicked")
for x in range(0, 10):
ttk.Button(root, name="but"+x,width="30", height=3, text=x).grid( column=0,
r.ow=0, padx=10, pady=5)
butok=ttk.Button(root, width="30", height=3, text=x, command=lambda var="but"+x:
gonow(var)).grid( column=0, row=0, padx=10, pady=5)
if __name__ == "__main__":
root.mainloop()
New update
b = tk.Button(frm_txt_json_case_btn, width="30", height=3, text=str(titulo+" "+cherep), fg=fcolor,relief=relifst, borderwidth=4,command=lambda titulo=titulo,wrd2srch=words2search,assumirrow=assumirrow,hiden_row=assumirrowr,resp_kib=resp_kiblog,repkib=repkib,urrrl=url_conf, jsump=jsonreq, explis=expectresq, frm_txt_json_case_tit=frm_txt_json_case_tit, inp_cond_protocol=inp_cond_protocol, resp_json=resp_json_input,lblexp=lblexpect, reqtxt=reqst_input,frm_txt_json_case_btn=frm_txt_json_case_btn: ChangConfWI(reqtxt, lblexp, frm_txt_json_case_tit, resp_json, inp_cond_protocol,urrrl, jsump, explis,frm_txt_json_case_btn,repkib,resp_kib,wrd2srch,hiden_row,assumirrow,titulo))
b.grid(column=colcount, row=rowcount, padx=10, pady=5)
buttonslst.append(b)
valbut=int(assumirrowr)-8
print(valbut)
print(buttonslst[valbut])
fvarbut=buttonslst[valbut]
print(fvarbut)
ttk.Button(frm_but_oknot, width="15", text="OK", image=photoOK, command=lambda assumirrow=assumirrow,filename=filename_report,exp=lblexpect,obs=resp_kiblog,urrrl=url_conf,tipo_de_conf=tipo_de_conf, resp_json_input=resp_json_input, reqst_input=reqst_input: savetoxls("geradorteste",resp_json_input,reqst_input, "OK",tipo_de_conf,urrrl,obs,exp,filename,assumirrow,fvarbut)).grid( column=0, row=0, padx=1, pady=15)
When you pass x to gonow, it is the index of the button, not the button itself. You could store the buttons in a list (note: the buttons, not the result of grid!), and then use the index:
buttons = []
for x in range(0, 3):
b = tk.Button(root, width=30, height=3, text=x, command=lambda x=x: gonow(buttons[x]))
b.grid(column=0, row=x, padx=10, pady=5)
buttons.append(b)
Or postpone the command creation after the button is created and pass the button itself:
for x in range(0, 3):
b = tk.Button(root, width=30, height=3, text=x)
b.config(command=lambda b=b: gonow(b))
b.grid(column=0, row=x, padx=10, pady=5)
(Note: There are a few more unrelated (syntax) errors throughout your code that you should fix.)
What I want the frame to do is that when I click on the 'clear' button, the frame is cleaned but it does not and when I enter a string that is not valid and then a valid one, it shows traces of the past and past action. I already tried changing the Label.grid () by a Label.pack (), but it is worse since the 'animation' looks like a stack without removing any element when the 'clear' button is pressed
This is basically what would make it change
from tkinter import *
import tkinter.ttk as ttk
def clear():
area.delete(0,END)
frame.config(bd=1, relief=SUNKEN)
frame.update()
status = Label(frame)
status.grid(row=0, column=0, sticky=NSEW)
def statusVal(value):
if not value == 0:
status = Label(frame, background="#ff4242", fg="#262626", text="Cadena invalida", anchor="center")
status.grid(row=0, column=0)
frame.config(bd=1, relief=SUNKEN, background="#ff4242")
frame.update()
else:
status = Label(frame, background="#56ed42", fg="#262626", text="Cadena valida", anchor="center")
status.grid(row=0, column=0)
frame.config(bd=1, relief=SUNKEN, background="#56ed42")
frame.update()
#Test
def validation():
capture = area.get()
if capture == '1':
return statusVal(0)
else:
return statusVal(1)
root = Tk()
root.geometry("300x150+300+300")
area = Entry(root)
area.grid(row=1, column=0, columnspan=2, sticky=E+W+S+N, padx=5)
frame = Frame(root, bd=1, relief=SUNKEN)
frame.grid(row=2, column=0, padx=5, pady=5, columnspan=2, sticky=W+E+S+N)
frame.columnconfigure(0,weight=5)
frame.rowconfigure(0,weight=5)
abtn = Button(root, text="Validate", command=validation)
abtn.grid(row=1, column=3)
cbtn = Button(root, text="Clear", command=clear)
cbtn.grid(row=2, column=3, pady=5)
root.mainloop()
See if this works better. The main change was to have the status Label always exist and hide or unhide it as desired — instead of creating a new one every time the validation() function was called. I also removed the code that was explicitly updating the frame which isn't necessary.
from tkinter import *
import tkinter.ttk as ttk
def clear():
area.delete(0,END)
status.grid_remove() # Hide. but remember grid options.
def statusVal(value):
if not value == 0:
status.config(background="#ff4242", fg="#262626", text="Cadena invalida",
anchor="center")
status.grid() # Unhide
else:
status.config(background="#56ed42", fg="#262626", text="Cadena valida",
anchor="center")
status.grid() # Unhide
#Test
def validation():
capture = area.get()
if capture == '1':
statusVal(0)
else:
statusVal(1)
# Main
root = Tk()
root.geometry("300x150+300+300")
area = Entry(root)
area.grid(row=1, column=0, columnspan=2, sticky=E+W+S+N, padx=5)
frame = Frame(root, bd=1, relief=SUNKEN)
frame.grid(row=2, column=0, padx=5, pady=5, columnspan=2, sticky=W+E+S+N)
frame.columnconfigure(0,weight=5)
frame.rowconfigure(0,weight=5)
# Initialize status Label.
status = Label(frame, anchor="center")
status.grid(row=0, column=0)
status.grid_remove() # Hide it.
abtn = Button(root, text="Validate", command=validation)
abtn.grid(row=1, column=3)
cbtn = Button(root, text="Clear", command=clear)
cbtn.grid(row=2, column=3, pady=5)
root.mainloop()