小编Cri*_*spy的帖子

Python Tkinter:删除字符串的最后一个字符

我正在创建一个只允许输入数字的条目.如果该字符不是整数,我目前仍然在删除刚刚输入的字符.如果有人将"BLANK"替换为需要进行的操作,那将会有很多帮助.

import Tkinter as tk

class Test(tk.Tk):

    def __init__(self):

        tk.Tk.__init__(self)

        self.e = tk.Entry(self)
        self.e.pack()
        self.e.bind("<KeyRelease>", self.on_KeyRelease)

        tk.mainloop()



    def on_KeyRelease(self, event):

        #Check to see if string consists of only integers
        if self.e.get().isdigit() == False:

            self.e.delete("BLANK", 'end')#I need to replace 0 with the last character of the string

        else:
            #print the string of integers
            print self.e.get()




test = Test()
Run Code Online (Sandbox Code Playgroud)

python tkinter tkinter-entry

5
推荐指数
1
解决办法
4615
查看次数

Django-ModelForm:添加不属于模型的字段

注意:将django-crispy-forms库用于我的表单。如果您有解决不使用cripsy_forms库的问题的解决方案,我将完全接受。不试图变得挑剔,只需要一个解决方案/解决。谢谢

在表单的Meta类中,我设置了模型,Driftwood它是我想要在表单中的字段,但是我也想添加另一个字段。不属于参考模型的模型。我要添加的字段是图像。此字段的原因是要从中构建另一个模型。

我有一个名为的模型Image,其中包含一些字段,这些字段可以通过单个操作来填充models.ImageField()。这Imagemodels.ForeginKey()Driftwood模型有关系。因此Image可以Driftwood使用其关系集属性(driftwood.image_set)通过的实例进行访问。

view.pygeneric.CreateView()用作将处理我的窗体类的继承的类。我计划使用该form_valid()方法来获取form.cleaned_data所需的图像。然后,我将创建图像,将object.id新实例化Driftwood的图像和图像传递到Image模型中。

但是,我的问题是不知道如何向FormModel不与表单关联的模型的Django添加自定义字段。

表格

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, ButtonHolder, Submit

from . import models

class DriftwoodForm(forms.ModelForm):
    class Meta:
        model = models.Driftwood
        fields = ('user', 'title', 'description')

    def __init__(self, *args, **kwargs): …
Run Code Online (Sandbox Code Playgroud)

python django django-forms django-crispy-forms

5
推荐指数
1
解决办法
2939
查看次数

Windows Python:使用语言环境模块更改编码

使用 Python 2.7

我正在编写一个抽象的网页抓取工具,但在显示(打印)某些字符时遇到了问题。

我收到回溯错误:UnicodeEncodeError: 'ascii' codec can't encode character u'\u2606' in position 5: ordinal not in range(128)从打印包含该字符的字符串。

我使用语言环境模块来找出我的操作系统支持的设置,虽然我不确定我是否应该使用语言环境来解决我的问题,并注意到默认设置(en_US', 'cp1252'). 我正在尝试将其更改为('en_US', 'utf-8')但遗憾的是无济于事。

#code for default settings
print locale.getdefaultlocale()
Run Code Online (Sandbox Code Playgroud)

这是我用来缩小语言环境设置选项的代码。(这里没有问题,代码只是让任何想要的人都可以跟随)

import locale
all = locale.locale_alias().items()
utfs = [(k,v) for k,v in all if 'utf' in k.lower() or 'utf' in v.lower()]

# utf settings starting with en
en_utfs = [(k,v) for k,v in utfs if k.lower()[:2].lower() == 'en' or 
            v.lower()[:2] == 'en'

print en_utfs
Run Code Online (Sandbox Code Playgroud)

这给出了输出:

[('en_ie.utf8@euro', …
Run Code Online (Sandbox Code Playgroud)

python encoding locale utf-8 setlocale

3
推荐指数
1
解决办法
5350
查看次数

何时在创建类时使用__init__

在使用Django一段时间之后,我习惯在没有def __init__(self): ...声明变量的情况下使用类.我曾经在__init__函数中声明我的变量,我现在意识到有些情况下不需要,我只是不清楚何时使用它.在尝试将类传递给变量时似乎存在问题,我应该在这些情况下使用init吗?

我知道我可以__init__用于所有情况,但它只是使我的短课程更像没有它的清洁,所以我想知道我什么时候可以使用它.

例:

class BaseScraper(object):
    # whithout __init__, passing Site() to site wont work.
    # site = Site()
    # parser = None

    def __init__(self):
        self.site = Site()
        self.parser = None 


class Site(object):
    # no trouble declaring url as a str
    url = ""

    def set(self, url):
        self.url = url

    def get(self):
        return self.url



if __name__ == "__main__":
    scraper = BaseScraper()

    scraper.site.set('http://www.google.com')   
    print scraper.site.get()
Run Code Online (Sandbox Code Playgroud)

python class

2
推荐指数
1
解决办法
116
查看次数

Python 套接字:gethostbyaddr:反向 DNS 查找失败

socket.gethostbyaddr(ip_addr)我在特定站点上使用时获取主机名时遇到问题。

我不会详细说明这不适用于哪个网站。

因此,通过名称获取主机对于到目前为止我尝试过的每个站点都可以正常工作,但是当我尝试从中获取站点名称时,我收到一条错误消息 ing host not found

修复或替代方案对于拥有完整的数据来说是很好的。如果没有解决办法,我只能省略主机名。没什么大不了的。谢谢您的帮助。

# not full code
hostip = socket.gethostbyname(hostname)
print socket.gethostbyaddr(hostip)

Error: socket.herror: [Errno 11004] host not found
Run Code Online (Sandbox Code Playgroud)

python sockets reverse-dns gethostbyaddr

2
推荐指数
1
解决办法
9370
查看次数

Python Tkinter标签背景透明

我有一个带有标签的窗口作为我的框架.我这样做是因为我想在后台拍摄一张照片.但是现在我遇到了我用过的其他标签的问题.我用来实际标记的其他标签没有透明的背景.有没有办法让这些标签的背景透明?

import Tkinter as tk

root = tk.Tk()
root.title('background image')

image1 = Tk.PhotoImage(file='image_name.gif')

# get the image size
w = image1.width()
h = image1.height()

# make the root window the size of the image
root.geometry("%dx%d" % (w, h))

# root has no image argument, so use a label as a panel
panel1 = tk.Label(root, image=image1)
panel1.pack(side='top', fill='both', expand='yes')

# put a button/label on the image panel to test it
label1 = tk.Label(panel1, text='here i am')
label1.pack(side=Top)

button2 = tk.Button(panel1, text='button2') …
Run Code Online (Sandbox Code Playgroud)

python label tkinter colors transparent

1
推荐指数
2
解决办法
2万
查看次数

Python Tkinter:当带有空格的字符串插入Listbox时,会出现括号

出于某种原因,在列表框中,字符串周围似乎有一个以空格结尾的括号.

from Tkinter import *

def update_listbox():   
    for i in dic:
        listbox.insert(END, (i, dic[i][0], dic[i][1], dic[i][2]))

dic = {}
dic['Foods'] = ['apple','grape','pizza']
dic['Drinks      '] = ['milk','soda','jucie'] # How do i make the {} not show up but keep the spaces?

root=Tk()
listbox = Listbox(root)
button = Button(root,text='push',command=update_listbox)
button.pack()
listbox.pack()


root.mainloop()
Run Code Online (Sandbox Code Playgroud)

python string listbox tkinter listboxitem

1
推荐指数
1
解决办法
2915
查看次数

如何计算与键关联的值的数量

鉴于以下字典,我想找出哪个键具有最多值.如果我有一个更长的字典并且想要以编程方式知道哪个键具有最多的值(没有目视检查),我将如何去做呢?我能想到的唯一方法如下:

dic = {'attacks': ['kick','puch','slap','elbow'], \
  'defense': ['block','parry','dodge']}
Run Code Online (Sandbox Code Playgroud)

dic = {'attack':['kick','puch','slap','elbow'],'defense':['block','parry','dodge']}

key_values_list = []
for key in dic:
    key_name = ''
    num = 0 
    for item in dic[key]:
        num +=1
    key_values_list.append((key,num))

for  k,v in key_values_list:
    print k,v
Run Code Online (Sandbox Code Playgroud)

python dictionary key find

1
推荐指数
2
解决办法
1974
查看次数

Python:赋值前引用的局部变量“字符串”

我想知道为什么从函数向该字符串添加字母时会出现此错误。
local variable 'string' referenced before assignment

代码

def update_string():
    string+='d'


string='s'

update_string()
Run Code Online (Sandbox Code Playgroud)

python string variables function

1
推荐指数
1
解决办法
1万
查看次数

Python类继承:dict如何pickle(保存,加载)

我正在玩类继承,我一直在研究如何在类字典中腌制数据.

如果只转换self的字典部分,当我将字典加载回self时,self会使用dict类型而不是类.但如果我挑选整个班级,那我就会收到错误.

错误

pickle.PicklingError: Can't pickle <class 'main.model'>: it's not the same object as main.model 
Run Code Online (Sandbox Code Playgroud)

import os, pickle

class model(dict):
    def __init__( self ):
        pass

    def add( self, id, val ): 
        self[id] = val

    def delete( self, id ):   
        del self[id]

    def save( self ): 
        print type(self)
        pickle.dump( dict(self), open( "model.dict", "wb" ) )

    def load( self ): 
        print 'Before upacking model.dic, self ==',type(self)
        self = pickle.load( open( "model.dict", "rb" ) ) 
        print 'After upacking model.dic, self ==',type(self)

if …
Run Code Online (Sandbox Code Playgroud)

python inheritance dictionary class pickle

1
推荐指数
1
解决办法
1390
查看次数