How do i set text input as int in kivy - python

i am trying to set the kivy textinput as an int to use it as a variable, which will be used to send a certain amount of messages.
This is my code:
import pyautogui
import time
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
class layy(App):
def build(self):
b = Button(text='Start Spam')
b.bind(on_press=self.bott())
layout = BoxLayout(orientation='vertical')
sublay1 = BoxLayout(orientation='horizontal')
sublay2 = BoxLayout(orientation='horizontal')
sublay3 = BoxLayout(orientation='horizontal')
layout.add_widget(sublay1)
sublay1.add_widget(a)
layout.add_widget(sublay2)
sublay2.add_widget(c)
sublay2.add_widget(d)
layout.add_widget(sublay3)
sublay3.add_widget(b)
return layout
def bott(self):
global a
a = TextInput(hint_text='insert text to spam')
global c
c = TextInput(hint_text=' insert time till beginning',
input_filter='int')
global d
d = TextInput(hint_text='insert amount', input_filter='int')
value3 = a
global ti
ti = value3.text
ii = int(c)
tt = int(d)
base = 0
time.sleep(tt)
while base < ii:
pyautogui.typewrite(ti)
pyautogui.press('enter')
base = base + 1
if __name__ == '__main__':
layy().run()
This is the error:
Traceback (most recent call last):
File "/home/fares/PycharmProjects/droidspm/main.py", line 67, in <module>
layy().run()
File "/home/fares/PycharmProjects/pythonProject/venv/lib/python3.8/site-packages/kivy/app.py", line 949, in run
self._run_prepare()
File "/home/fares/PycharmProjects/pythonProject/venv/lib/python3.8/site-packages/kivy/app.py", line 919, in _run_prepare
root = self.build()
File "/home/fares/PycharmProjects/droidspm/main.py", line 14, in build
b.bind(on_press = self.bott())
File "/home/fares/PycharmProjects/droidspm/main.py", line 52, in bott
ii= int(c)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'TextInput'
Are there any tips? I tried converting c and d to strings first but i got this error instead:
ValueError: invalid literal for int() with base 10: '<kivy.uix.textinput.TextInput object at 0x7f16597e7900>'
I cant seem to resolve the error, and i cant find anything online on how to. sorry if this is simple, i'm new to python.

On these specific lines:
ii = int(c)
tt = int(d)
You already got text using text property here, but why not for above?
ti = value3.text
value3(= a), b and c is all TextInput instances, it's just like you've been expecting to get integer by doing int(dict).
Plus, UI programing is usually made up with callbacks, writing sequential code with widgets just don't makes any sense. I'm not sure if your code worked as you've intended or not, but function bott won't wait until you actually type in something and keep on.
Here's simple demonstration of how kivy program would look like instead.
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
class InputField(TextInput):
def __init__(self, **kwargs):
super().__init__(multiline=False, input_filter = "int", **kwargs)
self.bind(on_text_validate=self.on_enter)
def on_enter(self, value):
output = int(value.text)
print(f"{output} - type: {type(output)}")
class MainApp(App):
def build(self):
layout_main = BoxLayout()
layout_main.add_widget(InputField())
return layout_main
if __name__ == '__main__':
MainApp().run()
for respective input of (123, 1230908):
123 - type: <class 'int'>
1230938 - type: <class 'int'>
Just using class InputField where you used TextInput would be enough - though use of global is hardly recommended, it will work.

Related

Python - Creating an instance of a module, getting an error

I am creating a universal text field that can be used in many python turtle projects. I am trying to create an instance of it but I get this error:
>>> import TextField
>>> tf = TextField('None', False)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
tf = TextField('None', False)
TypeError: 'module' object is not callable
>>>
What in a module causes this type of error? I completely wrote this module and I'm getting an error creating an instance of it :( ... What do I need in this module to make it 'callable'? I have tried adding a def __call__(self): but that doesn't affect the problem at all, nor create any errors.
Here is the beginning of the script where the problem is most likely happening:
# Created by SUPERMECHM500 # repl.it
# Edited by cdlane # stackoverflow.com
class TextField:
TextFieldBorderColor = '#0019fc'
TextFieldBGColor = '#000000'
TextFieldTextColor = '#ffffff'
ShiftedDigits = {
'1':'!',
'2':'#',
'3':'#',
'4':'$',
'5':'%',
'6':'^',
'7':'&',
'8':'*',
'9':'(',
'0':')'
}
def __init__(self, command, CanBeEmpty): # Ex. textField = TextField('Execute()', True)
self.CmdOnEnter = command
self.turtle = Turtle()
self.CanBeEmpty = CanBeEmpty
self.turtle.speed('fastest')
self.inp = []
self.FullOutput = ""
self.TextSeparation = 7
self.s = self.TextSeparation
self.key_shiftL = False
......
The module is not the class. If your class TextField is in a module called TextField, then it is referred to as TextField.TextField.
Or change your import to
from TextField import TextField

raise AttributeError(name) AttributeError: LCC_GetChannelHandle

I am very new in python cffi. I have to access my temprature module by using its Index or with its channel name. I am trying with both as you can see in my QmixTC class. I am getting attribute error. In other class, there is no errors. Can someone help me understand where is the problem. I am putting my code as well as error trace. Thanks.
main code with name qmix.py (importing it in to sample code):
class QmixTC (object):
"""
"""
def __init__(self, index=0, handle=None,name=''):
self.dll_dir = DLL_DIR
self.dll_file = os.path.join(self.dll_dir,
'labbCAN_Controller_API.dll')
self._ffi = FFI()
self._ffi.cdef(CONTROLLER_HEADER)
self._dll = self._ffi.dlopen(self.dll_file)
self._handle = self._ffi.new('dev_hdl *', 0)
if handle is None:
self.index = index
self._handle = self._ffi.new('dev_hdl *', 0)
self._call('LCC_GetChannelHandle', self.index, self._handle)
else:
self.index = None
self._handle = handle
self._ch_name="QmixTC_1_DO0_INA"
self._channel = self._ch_name + str(index)
self._call('LCC_LookupChanByName',
bytes(self._channel,'utf8'),
self._handle)
self.name = name
def _call(self, func_name, *args):
func = getattr(self._dll, func_name)
r = func(*args)
r = CHK(r, func_name, *args)
return r
def Setpoint_write (self, setpoint):
"""
Write setpoint value to controller device.
Parameters
[in] ChanHdl Valid handle of open controller channel
[in] fSetPointValue The setpoint value to write
Returns
Error code - ERR_NOERR indicates success
"""
self._call('LCC_WriteSetPoint', self._handle[0], setpoint)
def enable_controllLoop (self, enable):
"""
Enables / disables a control loop.
If the control loop is enabled, then the output value is calculated periodically.
Parameters
ChanHdl Valid handle of a controller channel
Enable 1 = enable, 0 = disable
Returns
Error code - ERR_NOERR indicates success
"""
self._call('LCC_EnableControlLoop', self._handle[0], enable)
def read_temp_value (self, actualvalue):
"""
Read actual value from device.
Parameters
[in] ChanHdl Valid handle of open controller channel
[out] pfActualValue Returns the actual controller value
Returns
Error code - ERR_NOERR indicates success
"""
self._call('LCC_ReadActualValue', self._handle[0], actualvalue)
if __name__ == '__main__':
import os.path as op
dll_dir = op.normpath('C:\\Users\\Ravikumar\\AppData\\Local\\QmixSDK')
config_dir = op.normpath('C:\\Users\\Public\\Documents\\QmixElements\\Projects\\QmixTC_Pump\\Configurations\\QmixTC_pump')
bus = QmixBus(config_dir=config_dir)
bus.open()
bus.start()
controller_0 = QmixTC(index=0)
controller_0.enable_controllLoop(1)
sample program:
from __future__ import division, print_function
from win32api import GetSystemMetrics
import numpy as np
import os
import qmix
import pandas as pd
#%% CHANNEL INITIALIZATION
if __name__ == '__main__':
dll_dir = ('C:\\Users\\Ravikumar\\AppData\\Local\\QmixSDK')
config_dir = ('C:\\Users\\Public\\Documents\\QmixElements\\Projects\\QmixTC_test1\\Configurations\\QmixTC_test1')
qmix_bus = qmix.QmixBus(config_dir=config_dir,dll_dir=dll_dir)
qmix_bus.open()
qmix_bus.start()
controller_0 = qmix.QmixTC(index=0)
controller_0.Setpoint_write(50)
error:
Traceback (most recent call last):
File "<ipython-input-5-40d4a3db9493>", line 17, in <module>
controller_0 = qmix.QmixTC(index=0)
File "qmix.py", line 921, in __init__
self._call('LCC_GetChannelHandle', self.index, self._handle)
File "qmix.py", line 937, in _call
func = getattr(self._dll, func_name)
File "C:\Users\Ravikumar\Anaconda2\lib\site-packages\cffi\api.py", line 875, in __getattr__
make_accessor(name)
File "C:\Users\Ravikumar\Anaconda2\lib\site-packages\cffi\api.py", line 870, in make_accessor
raise AttributeError(name)
AttributeError: LCC_GetChannelHandle

How to display SQL data into GUI list widget?

I was wondering how to display information from an database table onto a listwidget or something similar. This is for a flashcard app, and the one questions is supposed to show at a time. Then when the click to reveal button is clicked the corresponding answer is supposed to show, but at the moment nothing is shown in the list widgets.
I don't understand why nothing is being shown in the GUI.
Here is my Code -
from PyQt4 import QtGui
from PyQt4 import QtCore
import sys
import flashcard
import os
import sqlite3
class FlashCardApp(QtGui.QMainWindow, flashcard.Ui_MainWindow):
def __init__(self):
super(self.__class__,self).__init__()
self.setupUi(self)
self.questions = []
self.answers = []
self.currentQ = 0
self.RevealAnswerBtn.clicked.connect(self.disA)
def dispQ(self):
print("display question {}".format(self.currentQ+1))
self.listQuestionWidget.clear()
if self.questions:
self.listQuestionWidget.addItem(self.questions[self.currentQ])
def disA(self):
self.listAnswerWidget.clear()
if self.answers:
self.listAnswerWidget.addItem(self.answers[self.currentQ])
def setData (self, questions, answers):
self.questions = questions
self.answers = answers
def run(self):
print ("start")
self.currentQ = 0
self.dispQ()
def main():
questions = []
answers = []
connection = sqlite3.connect("login.db")
c = connection.cursor()
c.execute ("SELECT Question FROM Flashcards")
resultq = c.fetchall()
questions.append(resultq)
c.execute ("SELECT Answer FROM Flashcards")
resulta = c.fetchall()
answers.append(resulta)
connection.close()
app = QtGui.QApplication(sys.argv)
form = FlashCardApp()
form.setData(questions,answers)
form.run()
form.show()
app.exec_()
if __name__ == '__main__':
main()
but then i get this error -
Traceback (most recent call last):
File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 68, in <module>
main()
File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 63, in main
form.run()
File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 41, in run
self.dispQ()
File "C:/Users/joe gorsuch/OneDrive/A-Level/Computer Science/Computer Science Project/Program/Login Form/Ui/1.py", line 25, in dispQ
self.listQuestionWidget.addItem(self.questions[self.currentQ])
TypeError: arguments did not match any overloaded call:
QListWidget.addItem(QListWidgetItem): argument 1 has unexpected type 'list'
QListWidget.addItem(str): argument 1 has unexpected type 'list'

Python and tkinter: NameError: global name 'roomChange' is not defined

I'm receiving the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "D:\COMPUTER SCIENCE\Seating Plan\SeatingPlan TEST.py", line 205, in displayText
if roomChange.get().strip() == "":
NameError: global name 'roomChange' is not defined
When attempting to run the following code:
from tkinter import *
import tkinter.messagebox
def displayText():
""" Display the Entry text value. """
global roomChange
if roomChange.get().strip() == "":
tkinter.messagebox.showerror("Invalid Value", "Please enter a valid classroom name.")
else:
tkinter.messagebox.showinfo("Temporary Window", "Text value = " + roomChange.get().strip())
def roomChanger():
chrm = Tk()
chrm.title("Change Room")
chrm.wm_iconbitmap('./Includes/icon.ico')
chrm["padx"] = 40
chrm["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(chrm)
#Create a Label in textFrame
roomChangeLabel = Label(textFrame)
roomChangeLabel["text"] = "Enter name of classroom: "
roomChangeLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
roomChange = Entry(textFrame)
roomChange["width"] = 50
roomChange.pack(side=LEFT)
textFrame.pack()
roomChangeButton = Button(chrm, text="Submit", command=displayText)
roomChangeButton.pack()
chrm.mainloop()
testButton = Button(window, text='Change Room', command=roomChanger)
testButton.place(x = 825, y = 360)
Can anyone suggest a solution to my problem?
Thanks
In roomChanger() you assign to roomChange:
roomChange = Entry(textFrame)
so you need to mark that name as a global inside that function too. Add a global roomChange statement in that function.
displayText() on the other hand, never tries to assign to roomChange and the global statement in that function can safely be removed.
I had the same problem.
Here was my solution:
from tkinter import *
from tkinter import messagebox
Some sort of namespace glitch. That second line shouldn't be necessary. Technically from a syntax perspective import * implies import messagebox too because it's part of it all.
Use those two lines, take away import tkinter.messagebox

Class Variable Retrieval in Python

This is a GUI I’ve been writing for a script I already have working. What I’m struggling with here is retrieving the information in the textboxes.
Under the definition generate I am able to pop a name off of listx but I am unable to grab the local variable entry from any of the instances of the new_title_box class.
from Tkinter import *
import ttk
boxvar=""
folder=""
listx=[]
count = 1
myrow = 1
class new_title_box:
def __init__(self,name):
global myrow, count, listx
self.entry = StringVar()
self.name = name
self.name = ttk.Entry(mainframe,width=45,textvariable=self.entry)
self.name.grid(column=1,row=myrow+1,sticky=(N,W))
listx.append(name)
print(listx) ## For debugging to insure that it is working correctly, if it gives output it, this part works
myrow = myrow + 1
count=count+1
def make_new(*args):
new_title_box('box'+str(count))
def generate(*args):
global listx, boxvar
while len(listx) > 0:
boxvar=listx.pop(0)
print(boxvar) ## For debugging to insure that it is working correctly, if it gives output it, this part works
folder = boxvar.entry.get() ## Not working here
print(folder) ## For debugging to insure that it is working correctly, if it gives output it, this part works
root = Tk()
root.title("File Maker")
mainframe = ttk.Frame(root, padding = "50 50 50 50")
mainframe.grid(column = 0,row = 0,sticky = (N, W, E, S))
mainframe.columnconfigure(0,weight=1)
mainframe.columnconfigure(0,weight=1)
add_entry = ttk.Button(mainframe,width=20, text = "add entry", command=make_new)
add_entry.grid(column=2,row=2,sticky=(N,W))
add_entry = ttk.Button(mainframe,width=20, text = "make files", command=generate)
add_entry.grid(column=2,row=3,sticky=(N,W))
root.mainloop()
Here's the traceback I'm getting:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter_init_.py", line 1442, in call
return self.func(*args)
File "C:\python\SampAqTkinter.py", line 28, in generate
folder = boxvar.entry ## Not working here
AttributeError: 'str' object has no attribute 'entry'
There are two things that need to be changed to fix the problem you describe:
In the new_title_box.__init__() method change: listx.append(name) to listx.append(self.name)
In the generate() function, change: folder = boxvar.entry.get() to folder = boxvar.get().
You are appending a string to listx, use self.name instead of the local string name

Categories

Resources