Please, help me. This is very strange.
Look at this:
#!/usr/bin/env python
from Tkinter import *
import database
def insertBook():
insertWindow = Tk()
insertWindow.title("Inserisci un nuovo romanzo nel database")
checkvars = []
checkvars.append(IntVar())
checkvars.append(IntVar())
Checkbutton(insertWindow, text = 'male', variable=checkvars[0]).pack()
Checkbutton(insertWindow, text = 'female', variable=checkvars[1]).pack()
Button(insertWindow, text= 'show', command=lambda: show(checkvars)).pack()
insertWindow.mainloop()
def show(checkvars):
print checkvars[0].get()
print checkvars[1].get()
class AppBase:
def __init__(self, parent):
self.quadro1 = Frame(parent)
self.quadro1.pack()
self.welcolmeLabel = Label(self.quadro1, text = "Benvenuto nel database dei romanzi di Lory")
self.welcolmeLabel.pack()
self.insertButton = Button(self.quadro1, command = insertBook);
self.insertButton["borderwidth"] = 1
self.insertButton["text"] = "Inserisci un libro nel database"
self.insertButton["background"] = "pink"
self.insertButton.pack(side = "left")
self.quadro2 = Frame(parent)
self.quadro2.pack()
self.searchButton = Button(self.quadro1);
self.searchButton["borderwidth"] = 1
self.searchButton["text"] = "Ricerca nel database"
self.searchButton["background"] = "blue"
self.searchButton.pack(side = "left")
self.showButton = Button(self.quadro1);
self.showButton["borderwidth"] = 1
self.showButton["text"] = "Mostra i generi di libro"
self.showButton["background"] = "violet"
self.showButton.pack(side = "left")
self.exitButton = Button(self.quadro2, text = "Uscita", borderwidth = 1, background = "red", command = self.quadro1.quit)
self.exitButton.pack(side = RIGHT, pady = 20)
if __name__ == '__main__':
mainFinestra = Tk()
mainFinestra.title('Database di Romanzi')
app = AppBase(mainFinestra)
listvars = []
listvars.append(IntVar())
listvars.append(IntVar())
Checkbutton(mainFinestra, text = 'male', variable=listvars[0]).pack()
Checkbutton(mainFinestra, text = 'female', variable=listvars[1]).pack()
Button(mainFinestra, text= 'show', command=lambda: show(listvars)).pack()
mainFinestra.mainloop()
It seems that checkbuttons variables are set only in the mainFinestra.
If I create checkbuttons in another new window (such as insertWindow), the variables in checkvars are always 0, even if the buttons are checked. Instead if I try to check the checkbutton in the mainFinestra, the function "show" returns 1 if they are checked. What's the difference? Please, this project is important to me.
Thanks
You're doing something that Tkinter isn't designed to do -- you're creating two instances of the class Tk. You should only ever create one instance, and only ever start one event loop.
If you need multiple windows, create instances of Tkinter.Toplevel.
Related
I'm creating a program that can trade currency using the binance API.
It works as intended (irrelevant code not included)
My problem is that I now want to make is possible to create several instances of the class Trade, in new pop up windows. I'm having trouble understanding how to achieve this in terms of creating new instances of the class Trade. Also I'm pretty sure that my use of self: self = Trade(top) dosen't make any sense (even though it works).
To sum it up:
I want to be able to click a button that starts a new instance of Trade(), so that I can use the methods in the class for two different trading routines at the same time in the same instance of the program. How?
I'll appreciate any form of help, including suggesting me to read up on something.
I'm sorry if im too noob.
Thx in advance.
class Trade(Frame):
stop_trading = False
amount_orders = 0
after_id = 0
def __init__(self, master=None):
Frame.__init__(self, master)
def change_orders(self):
if list_variable4.get() == 'TRUE':
if self.check_open_order() == False or self.amount_orders<2:
if self.delete_open_orders() == True and self.stop_trading != True:
self.create_orders()
...
def cron():
self.amount_orders += 1
if self.amount_orders > int(trade_cap_box.get(0.0, tk.END)):
message_window.insert(tk.END,'\nTrade Cycle Cap reached with {} trades'.format(self.amount_orders - 1))
cap_stop_trading()
if self.stop_trading != True:
message_window.insert(tk.END,'\nTrading Cycle Started{}'.format(self.amount_orders))
interval = int(rate_of_check_box.get(0.0, tk.END))
print('Trading!')
self.change_orders()
self.after_id = top.after(interval*1000*60, cron)
def start_trading():
self.amount_orders = 0
self.stop_trading = False
cron()
top = Tk()
top.geometry("600x500")
top.title('Trade Cron Job')
self = Trade(top)
message_window = Text(top, height=5, width=65)
message_window.place(x = 40,y = 10)
trading_symbol_box = Text(top, height=1, width=20)
trading_symbol_box.place(x = 200,y = 130)
default_trading_symbol = (self.config_data['configs']['symbol'])
if default_trading_symbol:
trading_symbol_box.insert(END, default_trading_symbol)
else:
trading_symbol_box.insert(END, "")
trading_symbol_labels = Label(top, text='Trading Symbol')
trading_symbol_labels.place(x = 40,y = 130)
start_value_box = Text(top, height=1, width=20)
start_value_box.place(x = 200,y = 160)
start_value_box.insert(END, 0)
start_value_labels = Label(top, text='Start Value To Progress From')
start_value_labels.place(x = 40,y = 160)
and so on...
top.mainloop()
You need to create an instance of Toplevel, then add the instance of Trade to that window.
def new_window():
window = Toplevel()
trade_frame = Trade(window)
trade_frame.pack(fill="both", expand=True)
...
new_window_button = Button(top, text="New Window", command=new_window)
I am trying to connect my tkinter code with another program. That is, I am trying to call the GUI file from the the other program and receive input from the GUI program, but I am having issues.
Here is the GUI code called BayeGUI
from tkinter import *
import tkinter.simpledialog
class BayeGUI:
def __init__(self):
window = Tk()
window.title('Graphical User Interface Designed by Gideon')
self.input = 'I am fine Thank you'
frame1 = Frame(window)
frame1.pack()
self.v1 = StringVar()
scrollbar = Scrollbar(frame1)
scrollbar.pack(side = RIGHT, fill = Y)
self.text = Text(frame1, width = 100, height = 30,wrap = WORD, yscrollcommand = scrollbar.set)
scrollbar.config(command = self.text.yview)
self.text.pack()
frame2 = Frame(window)
frame2.pack()
testbtn = Button(frame2,text = 'Test Algorithm',command = self.testAlgorithm)
testbtn.grid(row = 1, column = 1)
return self.input
window.mainloop()
def testAlgorithm(self):
isYes = tkinter.messagebox.askyesno('askyesno', 'Do you want to Test the Algorithm?')
if isYes == True:
self.input = self.text.get("1.0",'end-1c') #This is the input I need
BayeGUI()
This is the main code where I am trying to get value fron Baye GUI.
from BayeGUI import BayeGUI
emails = BayeGUI()
print(emails)
I am new in python and trying to make a program for converting a given string into a secret code. The string entered by user in the text box is taken as input and converted in secret code (using the encryption module). How do I display the result in the window (I tried using the label but it shows an error.)
from tkinter import *
import encryption as En # Loading Custom libraries
import decryption as De
out_text = None # Out text is the output text of message or the encryption
root = None
font_L1 = ('Verdana', 18, 'bold') # The font of the header label
button1_font = ("Ms sans serif", 8, 'bold')
button2_font = ("Ms sans serif", 8, 'bold')
font_inst = ("Aerial", 8)
my_text = None
input_text = None
text_box = None
resut_l = None
result_2 = None
def b1_action(): # Encryption button
input_text = text_box.get()
if input_text == "":
print("Text field empty")
else:
En.enc_text(input_text) # Message is returned as 'code'
def b2_action():
input_text = text_box.get()
if input_text == "":
print("Text field Empty")
else:
De.dec_text(input_text)
def enc_button(): # Button for rendering encryption
b1 = Button(root, text = "ENCRYPT", font = button1_font, command = b1_action)
b1.configure(bg = 'palegreen3', width = '10', height = '3')
b1.place(x = '120', y = '130')
def dec_button(): # Button for decryption
b2 = Button(root, text = "DECRYPT", font = button2_font, command = b2_action)
b2.configure(bg = 'palegreen3', width = '10', height = '3')
b2.place(x = '340', y = '130')
def main(): #This is the core of GUI
global root
global text_box
root = Tk()
root.geometry("550x350")
root.configure(bg = "MediumPurple1")
win_text = Label(root, text = 'Enter text below and Choose an action:', bg = 'MediumPurple1', font = font_L1)
win_text.place(x = '10', y = '50')
text_box = Entry(root, text = 'Enter the Text', width = 60, bg = 'light blue')
text_box.place(x = '100', y = '100')
inst_text = Label(root, text = instructions, bg = "MediumPurple1", font = font_inst)
inst_text.pack(side = BOTTOM)
enc_button()
dec_button()
root.title('Secret Message.')
root.mainloop()
main()
And here is the encryption module
def enc_text(line):
msg = str(line).replace(' ', '_').lower()
msg_list = list(msg)
all_char = list("abcdefghijklmnopqrstuvwxyzabc_!?#")
for i in range(0, len(msg)):
pos_replaced = all_char.index(str(msg_list[i])) #will give the positon of the word to be replaced in the main list of alphabets
msg_list.insert(i, all_char[pos_replaced + 3]) #will replace the elements one by one
msg_list.pop(i + 1)
i += 1
code = ''.join(msg_list).replace('#', ' ')
print(code)
You can also suggest some improvisations.
Part of the problem is that Entry widgets don't have a text= configuration option, so it's completely ignored in the line:
text_box = Entry(root, text='Enter the Text', width=60, bg='light blue')
The best way to handle the character contents of an Entry is by using its textvariable= option and setting the value of it to be an instance of a tkinter.StringVar, then the getting and setting the value of that object will automatically update the Entry widget on the screen.
Below is your code with changes made to it to do this. Note I commented and changed a few unrelated things to be able to run the code, but tried to indicate the most important ones. Also note I added a return code statement at the very end of the enc_text() function in your custom encryption module.
from tkinter import *
import encryption as En # Loading Custom libraries
#import decryption as De # DON'T HAVE THIS.
out_text = None # Out text is the output text of message or the encryption
root = None
font_L1 = ('Verdana', 18, 'bold') # The font of the header label
button1_font = ("Ms sans serif", 8, 'bold')
button2_font = ("Ms sans serif", 8, 'bold')
font_inst = ("Aerial", 8)
my_text = None
input_text = None
text_var = None # ADDED.
text_box = None
resut_l = None
result_2 = None
# CHANGED TO USE NEW "text_var" variable.
def b1_action(): # Encryption button
input_text = text_var.get()
if input_text == "":
print("Text field empty")
else:
text_var.set(En.enc_text(input_text))
def b2_action():
input_text = text_box.get()
if input_text == "":
print("Text field Empty")
else:
"""De.dec_text(input_text)"""
def enc_button(): # Button for rendering encryption
b1 = Button(root, text="ENCRYPT", font=button1_font, command=b1_action)
b1.configure(bg='palegreen3', width='10', height='3')
b1.place(x='120', y='130')
def dec_button(): # Button for decryption
b2 = Button(root, text="DECRYPT", font=button2_font, command=b2_action)
b2.configure(bg='palegreen3', width='10', height='3')
b2.place(x='340', y='130')
def main(): #This is the core of GUI
global root
global text_box
global text_var # ADDED
root = Tk()
root.geometry("550x350")
root.configure(bg="MediumPurple1")
win_text = Label(root, text='Enter text below and Choose an action:',
bg='MediumPurple1', font=font_L1)
win_text.place(x='10', y='50')
text_var = StringVar() # ADDED
text_var.set('Enter the Text') # ADDED
# CHANGED text='Enter the Text' to textvariable=text_var
text_box = Entry(root, textvariable=text_var, width=60, bg='light blue')
text_box.place(x='100', y='100')
inst_text = Label(root, text="instructions", bg="MediumPurple1",
font=font_inst)
inst_text.pack(side=BOTTOM)
enc_button()
dec_button()
root.title('Secret Message.')
root.mainloop()
main()
I am very new on Python and I have a problem.
I try to read my temperature sensor and set the Value in to my Tkinter GUI.
I don't know how to update my label LT with the new value if I update it with my Button B1.
I have tried everything from StringVar to get() and this stuff.
I hope you can help me to find my failure.
Here is my code:
from tkinter import *
import os
Main = Tk()
Main.title("Hauptmenü")
Main.geometry("500x400")
class Fenster():
def Credit():
messagebox.showinfo(title="Credits",message="created by T.N v0.1")
return
def Beenden():
pExit = messagebox.askyesno(title="Beenden",message="Möchten Sie\n wirklich beenden?")
if pExit > 0:
Main.destroy()
return
def auslesen(event):
file = open("/sys/bus/w1/devices/28-041635ad4cff/w1_slave")
inhalt = file.read()
trennwoerter = inhalt.split(" ")
Wert = (trennwoerter[20])
Temp = (Wert[2:4])
file.close()
labelauslesen = Label(Main,text="Aktuelle Temperatur :")
labelauslesen.pack()
LT = Label(Main,text=Inhalt)
LT.pack()
B1 = Button(Main,text="Temperatur auslesen")
B1.pack()
B1.bind("<Button-1>",auslesen)
menubar=Menu(Main)
filemenu = Menu(menubar)
filemenu.add_command(label="Sensoren auslesen")
filemenu.add_command(label="Diagram anzeigen")
filemenu.add_command(label="Credits",command = Credit)
filemenu.add_command(label="Beenden",command = Beenden)
menubar.add_cascade(label="Datei",menu=filemenu)
Main.config(menu=menubar)
mainloop()
A minimal example that you can adapt to your code.
import tkinter as tk
root=tk.Tk()
temp = 10.0
def update_temp():
global temp
temp += 1.3
tlabel['text'] = '%s degrees C' % round(temp, 1)
tlabel = tk.Label(root, text='unknown')
tbutton = tk.Button(root, text='new temp', command=update_temp)
tlabel.pack()
tbutton.pack()
root.mainloop()
I haven't figured out how to set the focus on a specific tab of a ttk.Notebook. focus_set does not work. Is there any possibility?
Thanks in advance
I was having the same problem. What I found is the 'select' method for notebooks (ttk.Notebook.select(someTabFrame)) solves this problem:
import ttk, Tkinter
mainWindow = Tkinter.Tk()
mainFrame = Tkinter.Frame(mainWindow, name = 'main-frame')
mainFrame.pack(fill = Tkinter.BOTH) # fill both sides of the parent
nb = ttk.Notebook(mainFrame, name = 'nb')
nb.pack(fill = Tkinter.BOTH, padx=2, pady=3) # fill "master" but pad sides
tab1Frame = Tkinter.Frame(nb, name = 'tab1')
Tkinter.Label(tab1Frame, text = 'this is tab 1').pack(side = Tkinter.LEFT)
nb.add(tab1Frame, text = 'tab 1')
tab2Frame = Tkinter.Frame(nb, name = 'tab2')
Tkinter.Label(tab2Frame, text = 'this is tab 2').pack(side = Tkinter.LEFT)
nb.add(tab2Frame, text = 'tab 2')
nb.select(tab2Frame) # <-- here's what you're looking for
mainWindow.mainloop()
python docs for ttk.Notebook:
https://docs.python.org/2/library/ttk.html#ttk.Notebook
I also used this blog post as a model for my code:
http://poquitopicante.blogspot.com/2013/06/blog-post.html
This code based on wordsforthewise's answer to this question. Here you can find example of using select as get and set function, it shown by button that switch between 2 tabs.
small improvement:
import ttk, Tkinter
from pango import Weight
from Tkinter import Button
tab2Frame = None
tab1Frame = None
def switchTab():
if nb.select()[-1] == "1":
nb.select(tab2Frame)
elif nb.select()[-1] == "2":
nb.select(tab1Frame)
mainWindow = Tkinter.Tk()
mainWindow.geometry("%dx%d+0+0" % (200, 200))
mainFrame = Tkinter.Frame(mainWindow, name = 'main-frame')
mainFrame.pack(fill = Tkinter.BOTH) # fill both sides of the parent
button = Button(mainWindow, text = "Switch", command = switchTab)
button.configure(width = 15, activebackground = "#6f6Fff")
button.pack()
nb = ttk.Notebook(mainFrame, name = 'nb')
nb.pack(fill = Tkinter.BOTH, padx=2, pady=3) # fill "master" but pad sides
tab1Frame = Tkinter.Frame(nb, name = 'tab1')
Tkinter.Label(tab1Frame, text = 'this is tab 1').pack(side = Tkinter.LEFT)
nb.add(tab1Frame, text = 'tab 1')
tab2Frame = Tkinter.Frame(nb, name = 'tab2')
Tkinter.Label(tab2Frame, text = 'this is tab 2').pack(side = Tkinter.LEFT)
nb.add(tab2Frame, text = 'tab 2')
mainWindow.mainloop()