I have this section of code that is not working properly. Was wondering whether anyone could understand what is wrong with it?
import os
from tkinter import *
import time
import sys
root = Tk()
root.attributes("-fullscreen", True)
class User_Questions:
def __init__(self, master):
self.master = master
master.title("MIT")
global frame
frame = Frame(master)
frame.pack()
self.choosen_questions = []
self.choosen_answers = []
self.choosen_questions_file = open(os.path.expanduser("~/Desktop/Bradfield/Project/" + str(test_choice) + "/Questions.txt"))
self.choosen_answers_file = open(os.path.expanduser("~/Desktop/Bradfield/Project/" + str(test_choice) + "/Answers.txt"))
for line in self.choosen_questions_file:
self.new_question = line.replace("\n","")
self.choosen_questions.append(self.new_question)
for line in self.choosen_answers_file:
self.new_answer = line.replace("\n","")
self.choosen_answers.append(self.new_answer)
self.correct_answers = 0
self.question_label = Label(frame, text = self.choosen_questions[0].replace("1. ",""), font = "Helvetica", fg = "blue")
self.question_label.pack()
self.answer_entry = Entry(frame, text = "", font = "Helvetica")
self.answer_entry.pack()
self.answer_entry.bind('<Return>', self.question)
self.check_test_exists_button = Button(frame, text="SUBMIT", font = "Helvetica", command=self.question)
self.check_test_exists_button.pack()
self.back_button = Button(frame, text="GO BACK", font = "Helvetica", command=self.go_back)
self.back_button.pack()
self.quit_button = Button(frame, text="QUIT", font = "Helvetica", command=master.destroy)
self.quit_button.pack()
def question(self, event):
for i in range(1, len(self.choosen_questions)):
return(self.choosen_questions[i+1].replace(i+". ",""))
def go_back(self):
frame.destroy()
my_gui = User_Choose_Test(root)
This is the error that outputs:
AttributeError: 'User_Questions' object has no attribute 'question'
The indentation of question and go_back is incorrect. It needs to be un-indented one level.
Related
The scrollbar activates only when the window is rezised, despite reconfiguring the scrollregion everytime a widget(Button in this case) is added.
class Editor:
def __init__(self,master):
self.master = master
self.master.resizable(True,False)
self.edit_frame = tk.Frame(self.master)
self.edit_frame.pack(fill="none")
self.elem_frame = tk.Frame(self.master,width=700)
self.elem_frame.pack(fill="y", expand=1)
self.my_canvas = tk.Canvas(self.elem_frame, width = 700)
self.my_canvas.pack(side = "left", fill="both", expand=1)
my_scrollbar = ttk.Scrollbar(self.elem_frame, orient = "vertical", command =self.my_canvas.yview)
my_scrollbar.pack(side = "right",fill="y")
self.my_canvas.configure(yscrollcommand=my_scrollbar.set)
self.my_canvas.bind('<Configure>', self.movescroll )
self.second_frame = tk.Frame(self.my_canvas, bg = "black", width=700)
self.my_canvas.create_window((0,0), window=self.second_frame, anchor="nw")
self.naz = Nazioni()
paesi = [*self.naz.iso3]
print(paesi)
self.comb_paese = ttk.Combobox(self.edit_frame, value = paesi)
self.comb_paese.current(1)
self.kwordvar= tk.StringVar()
entry_keyword = tk.Entry(self.edit_frame, textvariable=self.kwordvar)
entry_keyword.bind("<FocusOut>", self.callback)
writer = tk.Text(self.edit_frame)
self.edit_frame.pack(side="left")
writer.pack()
self.comb_paese.pack()
entry_keyword.pack()
def callback(self, *args):
kword = self.kwordvar.get()
self.colonnarisultati(kword)
def colonnarisultati(self, keyword):
#TROVA IL VALORE CODICE ISO A 3CHAR IN BASE ALLA NAZIONE NEL COMBOBOX
p = self.comb_paese.get()
paese = self.naz.iso3[p]
ricerca = Ricerca(paese, keyword)
"""
for label in self.elem_frame.winfo_children():
label.destroy()
"""
self.count = 0
print("ciao")
for x in ricerca.listaricerca:
tit = str(x['titolo']).lstrip("<h4>").rstrip("</h4>")
print(tit)
self.elementotrovato(tit,self.count)
self.count +=1
self.my_canvas.configure(scrollregion=self.my_canvas.bbox("all"))
def movescroll(self, *args):
self.my_canvas.configure(scrollregion=self.my_canvas.bbox("all"))
def elementotrovato(self, testobottone, conta):
Bott_ecoifound = tk.Button(self.second_frame, text = testobottone,width = 100 ,height = 30, font = ("Helvetica", 12, "bold"), wraplength=200, justify="left")
print("CIAONE")
Bott_ecoifound.pack(fill="both", expand=1)
self.my_canvas.configure(scrollregion=self.my_canvas.bbox("all"))
The last method is the one adding button to the scrollable frame.
After the window is manually resized, no matter if back to its original size, the scrollbar activates and works fine.
I'm trying to make a program that has a button that will open a picture if a variable is in a certain state, and change how the button looks (or maybe show a different picture) if it's not. I have been trying to work through the bugs I've been getting.
This is honestly intermediary code so I can understand how to make what I'm actually trying to do, make a network-enabled GUI for some physical buttons.
I've tried passing blueButton in as a variable, but that didn't work.
import tkinter as tk
weather = "sunny"
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.blueButton = tk.Button(self, fg = "blue")
self.blueButton["text"] = "I'm Blue"
self.blueButton["command"] = self.change
self.blueButton.pack(anchor="nw")
self.quit = tk.Button(self, text = "QUIT", fg = "red",
command = self.master.destroy)
self.quit.pack(side="bottom")
self.pack(fill = "both", expand = 1)
def change(self):
global weather
if weather == "sunny":
w = tk.Canvas(root, width=400, height=750)
img = tk.PhotoImage(file = "haunter.gif")
w.create_image((200, 200), image = img)
w.pack()
else:
self.blueButton["bitmap"] = "error"
root = tk.Tk()
root.geometry("400x300")
app = Application(master = root)
app.mainloop()
The canvas gets made, but the picture doesn't show up, the "quit" button just moves.
I've also gotten the error "name blueButton is not defined".
You could keep the image as an attribute of your App, put it on a canvas, then show or hide the canvas depending on the weather.
import random
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.blueButton = tk.Button(self, fg = "blue")
self.blueButton["text"] = "I'm Blue"
self.blueButton["command"] = self.change
self.blueButton.pack()
self.quit = tk.Button(self, text = "QUIT", fg = "red",
command = self.master.destroy)
self.quit.pack()
self.pack(fill = "both", expand = 1)
self.canvas = tk.Canvas(root, width=400, height=750)
# self.sunny_img = tk.PhotoImage(file="haunter.gif")
self.sunny_img = tk.PhotoImage(file="rapporteur.gif")
self.canvas.create_image((200, 200), image=self.sunny_img)
def change(self):
weather = ['sunny', 'rainy']
current_weather = random.choice(weather)
if current_weather == 'sunny':
self.canvas.pack()
self.blueButton["bitmap"] = ''
else:
self.canvas.pack_forget()
self.blueButton["bitmap"] = "error"
root = tk.Tk()
root.geometry("400x300")
app = Application(master = root)
app.mainloop()
I'm trying to do a Canvas that display a picture in a new window with a pressing a button, actually that is working, but I need the display that show the image in the new windows resize to the new window dimension.
I already tried to manage to get the size to an specific but nothing really worked out for me.
Here is the code:
from tkinter import *
import requests
import shutil
from xml.dom.minidom import parse
import fileinput
import os.path as path
import os
import tempfile
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
root = Tk()
root.title("Etiquetas")
root.configure(width=1280,height=720)
root.geometry('{}x{}'.format(427, 600))
root.resizable(width=False, height=False)
canvas = Canvas(root, width=500, height=500)
canvas.pack(fill="both", expand=True)
my_image = PhotoImage(file='label.png')
def new_winF(): # new window definition
newwin = Toplevel(root)
display = Label(newwin, text="Humm, see a new window !")
display.pack()
def retrieve_input():
f = open('DataXML.xml', 'w+')
f.truncate(0)
inputParamString = ParamString.get("1.0","end-1c")
inputAlto = Alto.get("1.0","end-1c")
inputAncho = Ancho.get("1.0","end-1c")
inputTemplateLabel = TemplateLabel.get("1.0","end-1c")
#StringEtiqueta = open("DataXML.xml", "a+")
f.write(inputParamString)
f.close()
doc = parse("DataXML.xml")
my_node_list = doc.getElementsByTagName("label_param")
LabelResultado = open("Template.txt", "w")
LabelResultado.write(inputTemplateLabel)
LabelResultado.close()
for node in my_node_list:
name_node = node.getElementsByTagName("name")
value_node = node.getElementsByTagName("value")
y = ("[" + name_node[0].firstChild.data + "]")
z = y.upper()
print(z)
if (value_node[0].firstChild != None):
print(value_node[0].firstChild.data)
x = value_node[0].firstChild.data
else:
print("")
x = ""
with fileinput.FileInput("Template.txt", inplace=True) as file:
for line in file:
print(line.replace(z, x), end='')
w = open('Template.txt.bak', 'w+')
w.close()
codigoZPL = open("Template.txt", "r")
zpl = codigoZPL.read()
codigoZPL.close()
url = ('http://api.labelary.com/v1/printers/8dpmm/labels/'+inputAlto+'x'+inputAncho+'/0/')
files = {'file': zpl}
#headers = {'Accept': 'application/pdf'}
response = requests.post(url, headers=0, files=files, stream=True)
if response.status_code == 200:
response.raw.decode_content = True
with open('label.png', 'wb') as out_file: # change file name for PNG images
shutil.copyfileobj(response.raw, out_file)
else:
print('Error: ' + response.text)
newwin = Toplevel(root)
ncanvas = Canvas(newwin, width=500, height=500)
canvas.pack(fill="both", expand=True)
my_image = PhotoImage(file='label.png')
display = canvas.create_image(850, 50, anchor=NE, image=my_image)
line = canvas.create_line(0, 0, 0, 0)
display.pack()
root.mainloop()
def click_limpiar():
Alto.delete(0.0, END)
Ancho.delete(0.0, END)
ParamString.delete(0.0, END)
TemplateLabel.delete(0.0, END)
def close_window():
root.destroy()
exit()
#Crear un label
Label (text="Ingresar ParamString: ") .place(x=10,y=15)
Label (text="Ingresar TamaƱo (pulgadas): ") .place(x=10,y=160)
Label (text="Ingresar TemplateLabel: ") .place(x=10,y=218)
#Crear un textbox
ParamString = Text(root)
ParamString.pack()
ParamString.place(x=12, y=50, height=100, width=400)
Alto = Text(root)
Alto.pack()
Alto.place(x=12, y=190, height=20, width=20)
Ancho = Text(root)
Ancho.pack()
Ancho.place(x=52, y=190, height=20, width=20)
TemplateLabel = Text(root)
TemplateLabel.pack
TemplateLabel.place(x=12, y=250, height=300, width=400)
#Botones
Button(root, text="Aceptar", width=16, command=retrieve_input) .place(x=20,y=560)
Button(root, text="Limpiar", width=16, command=click_limpiar) .place(x=150,y=560)
Button(root, text="Salir", width=16, command=close_window) .place(x=280,y=560)
app = Window(root)
root.mainloop()
The Canvas part is this one:
newwin = Toplevel(root)
ncanvas = Canvas(newwin, width=500, height=500)
canvas.pack(fill="both", expand=True)
my_image = PhotoImage(file='label.png')
display = canvas.create_image(850, 50, anchor=NE, image=my_image)
line = canvas.create_line(0, 0, 0, 0)
display.pack()
Thanks in advance,
I am trying to create an application in Python GUI using tkinter. Here is the code I'm using for the GUI part. Whenever I try to access my Entry Widget I get error.
Ex:Sin_put.get() should give me the text in the Entry widget but it gives me an error
AttributeError: 'NoneType' object has no attribute 'get'
I'm relatively new to Python. So if you guys have any suggestions to improve the functionality you're most welcome.
from tkinter import *
from tkinter import ttk
sys.path.insert(0, 'home/ashwin/')
import portscanner
class App:
def __init__(self, master):
master.option_add('*tearOff', False)
master.resizable(False,False)
self.nb = ttk.Notebook(master)
self.nb.pack()
self.nb.config(width=720,height=480)
self.zipframe = ttk.Frame(self.nb)
self.scanframe = ttk.Frame(self.nb)
self.botframe = ttk.Frame(self.nb)
self.mb = Menu(master)
master.config(menu = self.mb)
file = Menu(self.mb)
info = Menu(self.mb)
self.mb.add_cascade(menu = file, label = 'Tools')
self.mb.add_cascade(menu = info, label = 'Help')
file.add_command(label='Zip Cracker', command = self.zipframe_create)
file.add_command(label='Port Scanner', command = self.scanframe_create)
file.add_command(label='Bot net', command =self.botframe_create)
info.add_command(label='Usage', command=(lambda:print('Usage')))
info.add_command(label='About', command=(lambda:print('About')))
def zipframe_create(self):
self.nb.add(self.zipframe,text='Zip')
self.zipframe.config(height=480,width=720)
zlabel1 = ttk.Label(self.zipframe, text='Select the zip file').grid(row=0,column=0, padx=5, pady=10)
zlabel2 = ttk.Label(self.zipframe, text='Select the dictionary file').grid(row=2,column=0, padx=5)
ztext1 = ttk.Entry(self.zipframe, width = 50).grid(row=0,column=1,padx=5,pady=10)
ztext2 = ttk.Entry(self.zipframe, width = 50).grid(row=2,column=1,padx=5)
zoutput = Text(self.zipframe, width=80, height=20).grid(row=3,column=0,columnspan = 3,padx=5,pady=10)
zb1 = ttk.Button(self.zipframe, text='Crack', width=10).grid(row=0,column=2,padx=5,pady=10)
def scanframe_create(self):
self.nb.add(self.scanframe,text='Scan')
self.scanframe.config(height=480,width=720)
slabel1 = ttk.Label(self.scanframe, text='IP address').grid(row=0,column=0, padx=5, pady=10)
sin_put = ttk.Entry(self.scanframe, width = 50).grid(row=0,column=1,padx=5,pady=10)
soutput = Text(self.scanframe, width=80, height=20).grid(row=3,column=0,columnspan = 3,padx=5,pady=10)
sb1 = ttk.Button(self.scanframe, text='Scan', width=6,command= print('Content: {}'.format(sin_put.get()))).grid(row=0,column=2,padx=5,pady=10)
def botframe_create(self):
self.nb.add(self.botframe,text='Bot')
self.botframe.config(height=480,width=720)
blabel1 = ttk.Label(self.botframe, text='IP address').grid(row=0,column=0, padx=5, pady=10)
blabel2 = ttk.Label(self.botframe, text='Username').grid(row=1,column=0, padx=2)
blabel3 = ttk.Label(self.botframe, text='password').grid(row=2,column=0, padx=2)
btext1 = ttk.Entry(self.botframe, width = 30).grid(row=0,column=1,padx=5,pady=10)
btext2 = ttk.Entry(self.botframe, width = 30).grid(row=1,column=1)
btext2 = ttk.Entry(self.botframe, width = 30).grid(row=2,column=1)
boutput = Text(self.botframe, width=80, height=20).grid(row=3,column=0,columnspan = 3,padx=5,pady=10)
bb1 = ttk.Button(self.botframe, text='Connect', width=8).grid(row=2,column=2,padx=5,pady=10)
def main():
root = Tk()
feedback = App(root)
root.mainloop()
if __name__ == "__main__": main()
grid() returns None so sin_put will always equal None. Instead of passing the Tkinter ID to grid() you have to store it first if you want to reference it later. Note that for the Buttons, putting it all on one line is fine as you don't use the button's ID later.
sin_put=ttk.Entry(self.scanframe, width = 50) ## stores the return ID from Entry
sin_put.grid(row=0,column=1,padx=5,pady=10) ## don't catch return from grid as it is None
I am trying to migrate the code below (which is in tkinter) to pyqt. I am very new to pyqt. I could not get much details.
import os, sys, time
import os.path
import shutil
import sys
import Tkinter as tk
from Tkinter import *
root = Tk()
frame = Frame(root)
def enable_():
# Global variables
if (var.get()==1):
E5.config(state=NORMAL)
E5.insert(0, 1)
for c in checkbuttons:
c.config(state=NORMAL)
# disable test selection
else:
E5.delete(0, END)
E5.config(state=DISABLED)
for c in checkbuttons:
c.config(state=DISABLED)
# Select geometry
root.geometry("500x570+500+300")
root.title('Test Configure')
# Global variable declaration
global row_me
global col_me
row_me =9
col_me =0
L1 = Label ().grid(row=0,column=1)
Label (text='Target IP Address').grid(row=1,column=0)
E4 = Entry(root, width=20)
E4.grid(row=1,column=1)
L1 = Label ().grid(row=2,column=1)
variable = StringVar()
# Check button creation
var = IntVar()
var_mail = IntVar()
# Create check buttons
R1=Checkbutton(root, text = "Enable Test Suite Selection", variable = var, \
onvalue = 1, offvalue = 0, height=1, \
width = 20, command=enable_)
R1.grid(row=3,column=1)
R2=Checkbutton(root, text = "Send Email", variable = var_mail, \
onvalue = 1, offvalue = 0, height=1, \
width = 20)
R2.grid(row=3,column=2)
L5 = Label (text='Number of Loop').grid(row=4,column=0)
E5 = Entry(root, width=5)
E5.grid(row=4,column=1)
E5.config(state=DISABLED)
L2 = Label ().grid(row=21,column=1)
# List of Tests
bottomframe = Frame(root)
bottomframe.grid(row=24,column=1)
# Reset Button
configbutton = Button(bottomframe, text="Reset", fg="black")
configbutton.grid(row=24,column=2,padx=5, pady=0)
# Quit Button
configbutton = Button(bottomframe, text="Quit", fg="red")
configbutton.grid(row=24,column=3)
# Submit Button
blackbutton = Button(bottomframe, text="Submit", fg="black")
blackbutton.grid(row=24,column=4,padx=5, pady=0)
#Check buttons for test suite selection
test_suite_name=[name for name in os.listdir(".") if (os.path.isdir(name) and name.startswith('test-') )]
L34 = Label (text='Select Test Suite To Be Executed').grid(row=7,column=1)
L11 = Label ().grid(row=9,column=1)
row_me =9
col_me =0
checkbuttons = [create_checkbutton(name) for name in test_suite_name ]
for c in checkbuttons:
c.config(state=DISABLED)
# initiate the loop
root.mainloop()
I have written this code but I am not sure how to make the grid and location for each widget in pyqt:
import sys
from PyQt4 import QtGui
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
SubmitButton = QtGui.QPushButton("OK")
CancelButton = QtGui.QPushButton("Cancel")
ResetButton = QtGui.QPushButton("Reset")
edit1 = QLineEdit()
edit2 = QLineEdit()
cb = QtGui.QCheckBox('Enable Test suite selection', self)
cb.move(150, 100)
#cb.stateChanged.connect(self.changeTitle)
cb2 = QtGui.QCheckBox('Send mail', self)
cb2.move(300, 100)
# cb2.stateChanged.connect(self.changeTitle)
hbox = QtGui.QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(SubmitButton)
hbox.addWidget(CancelButton)
hbox.addWidget(ResetButton)
hbox.addWidget(edit1)
hbox.addWidget(edit2)
hbox.addWidget(cb)
hbox.addWidget(cb2)
vbox = QtGui.QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.setGeometry(100, 100, 500, 650)
self.setWindowTitle('HMI')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Thank you!
You can either do the designing part in your code or through a QT Designer which ships with PyQt4. and some examples can be found in the path C:\Python26\Lib\site-packages\PyQt4\examples and documentation in the path C:\Python26\Lib\site-packages\PyQt4\doc\html\modules.html if you are using windows. Hope this helps.